Unity单例对象封装
所有需要设置单例的对象继承一个单例基类 SingletonBase<T>
public class SingletonBase<T> where T:new() { private static T instance; public static T GetInstance() { if (instance == null) { instance = new T(); } return instance; } }
使用方法:【假设manager需要设置为单例对象,只需继承单例基类】
public class manager : SingletonBase<manager> { public string name=""; public int num = 1; }
测试:
void Start() { var m1=manager.GetInstance(); var m2 = manager.GetInstance(); Debug.Log(m1==m2); m1.name += "123"; m2.name += "456"; Debug.Log(m2.name); }
评论