1.单例类
public class SingleTon
{
private static SingleTon _Instance;
public static SingleTon Instance
{
get
{
if (_Instance =null )
{
_Instance = new SingleTon();
}
return _Instance;
}
}
}
2.继承于MonoBehaviour的 单例类写法
public class SingleTon : MonoBehaviour
{
private static SingleTon _Instance;
public static SingleTon Instance
{
get
{
if (_Instance ==null)
{
GameObject obj = new GameObject("SingleTon");
_Instance = obj.AddComponent<SingleTon>();
DontDestroyOnLoad(obj);
}
return _Instance;
}
}
}
3.简化版写法,继承于MonoBehaviour,适应场景中一定只存在一个此单例对象,必须是唯一的时候才可以适用
public class SingleTon : MonoBehaviour
{
public static SingleTon Instance;
void Awake()
{
Instance = this;
}
}
4.泛型单例类
public class SingleTon<T> where T : class, new()
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
_Instance = new T();
}
return _Instance;
}
}
}