哪一种是在 Unity 中获取实例的最佳实践

时间:2021-08-01 17:57:16

标签: c# unity3d

我已经阅读了许多论坛和答案,但我仍然不知道哪一个是在统一中获得实例的最佳和最常用的做法。

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
}

我想了解使用此功能的最有益方法。提前致谢。

3 个答案:

答案 0 :(得分:2)

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

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;
        }
    }
}

答案 1 :(得分:1)

除非您的项目很小,否则您当然不想遵循后一种方法,因为 findObjectOfType() 会增加搜索对象的开销

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

答案 2 :(得分:1)

如果您想在整个应用程序中使用单例,请考虑使用 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;
}

欲了解更多信息,请前往Lazy Initialization