普通单例

//普通的单例类我们一般这样来创建

public class SingleTon : MonoBehaviour
{
    private static SingleTon Instance = null;

    //防止外界New
    private SingleTon()
    {

    }

    private void Awake()
    {
        if(Instance == null) Instance = this;
        else Destroy(gameObject);
    }

}

单例框架 第一种 需要继承并挂载在游戏物体上 那么我们必须要先继承MonoBehaviour

//这里的where T 是泛型约束
public class SingleTon<T> : MonoBehaviour where T : SingleTon<T>
{
    public static T Instance
    {
        get;
        private set;
    }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = (T)this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}

单例框架 第二种 不需要继承并挂载在游戏物体

public class SingleScript<T> where T : new()
{
    private static T instance = default(T);

    public static T GetInstance()
    {
        if (instance == null)
        {
            instance = new T();
        }
        return instance;
    }
}

相关文章:

  • 2021-12-31
  • 2021-05-09
  • 2021-09-05
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
相关资源
相似解决方案