继承MonoBehavior的永久单例类的实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//继承MonoBehavior的单例
public class TMonoSingleton<T> : MonoBehaviour
where T : Component, IInitializabe
{
protected static T _instance;
public static T Instance
{
get{
if(_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null){
GameObject obj = new GameObject();
obj.name = typeof(T).Name ;
obj.AddComponent<T>();
}
}
return _instance;
}
}
public void Init()
{
//throw new System.NotImplementedException();
}
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
(_instance as T).Init();
}
else
{
Debug.Log(_instance.name);
Destroy(gameObject);
}
}
}
初始化接口
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IInitializabe
{
void Init();
}