【常用】单例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25601345/article/details/88548159
using UnityEngine;
using System.Collections;

/// <summary>
/// 脚本的单例类
/// </summary>
public class MonoSingleton<T> : MonoBehaviour where T:MonoSingleton<T>
{
    //public static T Instance { get; private set; }

    private static T instance;
    public static T Instance
    {
        //懒汉
        //按需分配,如果在Awake方法中需要调用,就在Awake方法中创建
        get
        {
            if (instance == null)
            {
                //在场景中查找已经存在的对象引用
                instance = FindObjectOfType(typeof(T)) as T;
                if (instance == null)
                { 
                    //创建脚本对象
                    string goName = "Singleton of "+typeof(T);
                    instance = new GameObject(goName).AddComponent<T>();
                }
                //子类可能需要在此执行一段代码……
                instance.Init();
            }
            return instance;
        }
    }

    //饿汉
    private void Awake()
    {
        //当场景切换时 不销毁当前游戏对象
        //DontDestroyOnLoad(gameObject);

        //Instance = this as T;
    }

    protected virtual void Init() { }
}

猜你喜欢

转载自blog.csdn.net/qq_25601345/article/details/88548159