单例模式的优点:
1、在不用重复创建类的情况下提供唯一全局访问。
2、在需要频繁使用的对象上使用单例模式可以减少内存开销。
3、不需要手动创建和销毁单例对象,只需要引用即可。
单例模式的缺点:
1、增加代码的耦合性,后期难以维护。
2、单例脚本不受CG控制,需要手动卸载。
单例模式的特性:在unity程序运行中有且只有一个实例。
继承MonoBehaviour的单例模板
public class Singleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
public static T Instance
{
get
{
//instance=null证明单例未被创建
if (_instance == null)
{
GameObject o = new GameObject($"Singleton{typeof(T).Name}");
_instance = o.AddComponent<T>();
DontDestroyOnLoad(o);
}
return _instance;
}
}
private void OnDestroy()
{
//注意释放
DestroyImmediate(gameObject);
}
}
用法
public class TestA : Singleton<TestA>
{
public int num = 1;
}
public class TestB : MonoBehaviour
{
private void Start()
{
Debug.LogError(TestA.Instance.num);
}
}
不继承MonoBehavior的单例模板
public class Singleton<T>
{
protected Singleton() { }
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Activator.CreateInstance<T>();
}
return _instance;
}
}
}
用法
public class TestSingleton : Singleton<TestSingleton>
{
public int num = 1;
}
public class test : MonoBehaviour
{
private void Start()
{
Debug.LogError(TestSingleton.Instance.num);
}
}