1.非Mono
public class Singleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
2.Mono类
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new GameObject(typeof(T).Name).AddComponent<T>();
}
return instance;
}
}
}
3.Mono类不销毁
using UnityEngine;
public class SingletonMonoDontDestroy<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
var obj = new GameObject(typeof(T).Name);
instance = obj.AddComponent<T>();
DontDestroyOnLoad(obj);
}
return instance;
}
}
}
如果场景中是手动拖上去的可以加上instance = FindObjectOfType();来判断 用FindObjectsOfType可以判断场景中是否存在多个
|