SingletonBase.cs
using UnityEngine;
public class SingletonBase<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _lock = new object();
public static T Instance
{
get
{
//线程锁
lock (_lock)
{
//场景中找 没有的话在创建
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null)
{
//如果没有就创建一个
GameObject singletonGo = new GameObject("Singleton_" + typeof(T).Name);
_instance = singletonGo.AddComponent<T>();
DontDestroyOnLoad(singletonGo);
}
return _instance;
}
}
}
}
使用方法
public class Test : SingletonBase<Test> //继承即可
{
private void Start()
{
//调用
Test.Instance.Log();
}
public void Log() {
Debug.Log("Test单例");
}
}