非Mono
public class Singleton<T> where T : new()
{
private static object _lock = new object();
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null) instance = new T();
}
}
return instance;
}
}
}
如果场景中是手动拖上去的可以加上instance = FindObjectOfType();来判断
用FindObjectsOfType可以判断场景中是否存在多个
如下:
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
_instance = singleton.AddComponent<T>();
}
}
return _instance;
}
}
}
}
using UnityEngine;
public class SingletonMonoDontDestroy<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
_instance = singleton.AddComponent<T>();
}
DontDestroyOnLoad(_instance.gameObject);
}
return _instance;
}
}
}
}