56 lines
1.6 KiB
C#
56 lines
1.6 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
|
|
{
|
|
// [SerializeField] private bool _isLoadNotDestory = true;
|
|
|
|
private static T instance;
|
|
private static object locker = new object();
|
|
|
|
|
|
protected virtual string Description => "无备注";
|
|
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (instance == null)
|
|
{
|
|
lock (locker)
|
|
{
|
|
T[] instances = FindObjectsOfType<T>();
|
|
if (FindObjectsOfType<T>().Length >= 1)
|
|
{
|
|
instance = instances[0];
|
|
for (int i = 1; i < instances.Length; i++)
|
|
{
|
|
#if UNITY_EDITOR
|
|
Debug.LogError($"{typeof(T)} 不应该存在多个单例!{instances[i].name}");
|
|
#endif
|
|
Destroy(instances[i]);
|
|
}
|
|
|
|
return instance;
|
|
}
|
|
|
|
if (instance == null && Application.isPlaying)
|
|
{
|
|
var singleton = new GameObject();
|
|
instance = singleton.AddComponent<T>();
|
|
singleton.name = "(singleton)_" + typeof(T);
|
|
}
|
|
else
|
|
{
|
|
// DontDestroyOnLoad(instance.gameObject);
|
|
}
|
|
}
|
|
// instance.hideFlags = HideFlags.None;
|
|
}
|
|
|
|
return instance;
|
|
}
|
|
}
|
|
}
|