哪一个是在Unity中获得实例的最佳实践



我读了很多论坛和答案,仍然,我很困惑哪一个是最好的和最常用的实践,以获得统一的实例。

public static game_code instance;
private void Awake()
{
instance = this;
}

并在另一个脚本(如

)中使用此实例
private game_code gameCode;
void Start()
{
gameCode = game_code.instance; // Do I have to cache the reference if I'm using 
// instance or directly use game_code.instance wherever 
// required in other scripts?
}

在开头缓存其他脚本的引用,如

private game_code gameCode; 
void Start()
{
gameCode=findObjectOfType<game_code>(); // use this reference in script wherever required
}

我想学习最有效的方法来使用它。提前谢谢你。

第一种方法更好,但不要忘记检查您是否已经创建了实例,否则您可能会创建多个实例,而只需要一个。

public class SomeClass : MonoBehaviour {
private static SomeClass _instance;
public static SomeClass Instance { get { return _instance; } }

private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
} else {
_instance = this;
}
}
}

您当然不希望采用后一种方法,除非您的项目很小,因为findObjectOfType()会增加搜索对象的开销

所以第一种方法,即单例模式,在需要在整个应用程序中在不同的脚本中访问对象时是最有用的。

如果你想在整个应用程序中使用单例,那么考虑使用Lazy,因为这个包装器可以确保线程安全,如果对象尚未初始化,这对于并发访问可能很重要

public class MyClass
{
private MyClass(){} //prevent creation of class outside this class

private static readonly Lazy<MyClass> _lazyInstance = new Lazy<MyClass>(()=> new MyClass());

public static MyClass Instance => _lazyInstance.Value;
}

查看延迟初始化

最新更新