C# 单例

  using UnityEngine;
  using System.Collections;

  public class Singleton<T> : MonoBehaviour where T : Component
  {
      private static readonly object syslock = new object();  //我叫他线程锁
      private static T _instance;
      public static T Instance
      {
          get
          {
              if (_instance == null)
              {
                  lock (syslock)
                  { //锁一下,避免多线程出问题
                      _instance = FindObjectOfType(typeof(T)) as T;
                      if (_instance == null)
                      {
                          GameObject obj = new GameObject(typeof(T).Name);
                          //obj.hideFlags = HideFlags.DontSave;
                          //obj.hideFlags = HideFlags.HideAndDontSave;
                          _instance = (T)obj.AddComponent(typeof(T));
                }
            }
        }
        return _instance;
    }
}
//  这是为了不要在切换场景时单例消失,可以删掉
public virtual void Awake()
{
    DontDestroyOnLoad(this.gameObject);
    if (_instance == null)
    {
        _instance = this as T;
    }
    else
    {
        Destroy(gameObject);
    }
}
public static bool IsBuild
{
    get
    {
        return _instance != null;
    }
}

      // Use this for initialization
      void Start()
      {

      }

      // Update is called once per frame
      void Update()
      {

      }
  }
  public class Button_config : Singleton<Button_config>
  {
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容