【Unity】通用MonoBehaviour单例

通用单例基类

  • 通用MonoBehaviour单例基类
  • 通用单例的基类用法

通用MonoBehaviour单例基类

public class Singleton<T,U> : MonoBehaviour where T : Singleton<T, U>, U
{
	private static T _Singleton;
	public static U GetSingleton
	{
		get
		{
			if(_Singleton == null)
			{
					_Singleton= GameObject.FindObjectOfType<T>();
                    if (_Singleton== null)
                    {
                        GameObject tempClone = new GameObject(typeof(T).Name);
                        GameObject.DontDestroyOnLoad(tempClone);

                        _Singleton = tempClone.AddComponent<T>();
                    }
			}
			return _Singleton;
		}
	}
	public virtual void Awake()
	{
		if (m_manager == null)
        {
            m_manager = this as T;
            GameObject.DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            if (m_manager != (this as T))
            {
                GameObject.Destroy(this.gameObject);
            }
        }
	}
}

通用单例的基类用法

public interface IDemoManager{
	//初始化
	void Init();
}

public class DemoManager: Singleton<DemoManager,IDemoManager>,IDemoManager 
{
	
	public void Init()
	{
		//DemoManager初始化
	}
	public void Info()
	{
		//该方法将被限制无法通过单例直接调用
	}
}
public class Demo
{
	public void start()
	{
		DemoManager.GetSingleton.Init();
	}
}

你可能感兴趣的:(Unity拓展,unity,c#,拓展类)