Unity 单例 泛型 Singleton C# 继承MonoBehaviour

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class MonoSinglton : MonoBehaviour where T: MonoSinglton
{


    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
                Debug.LogError( typeof(T).ToString() + " is NULL.");
            return _instance;
        }
    }

    private void Awake()
    {
        if (_instance != null)
        {
            //one more Initialize
            Debug.LogError(typeof(T).ToString() + " aready have one on" + _instance.gameObject.name);
        }
        _instance = this as T;//or  _instance = (T)this; 
        //call Init
        Init();
    }
    /// 
    /// 需要在awake初始化的请重载Init
    /// 
    protected virtual void Init()
    {
        //optional to override
    }
}

//how to use?  like this
public class yourSingleton : MonoSinglton
{
    protected override void Init()
    {
        //optional to override
    }

}

推荐使用这种,直接挂载于empty物件上的方式。这样,如果有需要一些prefab时,可以拉至脚本中。
不推荐使用当instance=null时new Gamaobject然后AddComponent的方式。
若不需要继承MonoBehaviour,请看
https://blog.csdn.net/u014234721/article/details/86524550

你可能感兴趣的:(泛型,Unity,单例,Singleton)