Unity中的泛型單例腳本工具

在Unity遊戲開發中,寫腳本經常會用到單例模式,所以就寫了一個公用的泛型單例類方便使用,也爲了以後開發偷點懶

 

public class Singleton<T> where T : class, new()
{
    public Singleton()
    {

    }

    private static T _instance;

    private static readonly object _synclock = new object();


    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_synclock)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
                }
            }
            return _instance;
        }
        set { _instance = value; }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章