????????总结学习的一些Unity常用的设计模式,还在不断学习补充中...
- 单例模式
using UnityEngine;
public class Singleton : MonoBehaviour
{
protected static Singleton s_Instance;
public static Singleton Instance => s_Instance;
private void Awake()
{
if (!ReferenceEquals(s_Instance, null))
{
Destroy(gameObject);
}
else
{
s_Instance = this;
}
}
private void OnDestroy()
{
if (s_Instance == this)
{
s_Instance = null;
}
}
} -
泛型单例模式
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
protected static T s_Instance;
public static T Instance => s_Instance;
protected virtual void Awake()
{
if (!ReferenceEquals(s_Instance, null))
{
Destroy(gameObject);
}
else
{
s_Instance = (T) this;
}
}
protected virtual void OnDestroy()
{
if (s_Instance == this)
{
s_Instance = null;
}
}
} -
... - ...
- ...
- ...
|