unity的日常学习
目录
单例模式
让一个类只能创建一次。解决对象的唯一性,保证了内存中一个对象是唯一的 。
可以简化代码是游戏编码中一种常用的设计模式
一般的形式
public class danli : MonoBehaviour
{
private static danli instance;
public static danli Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<danli>();
}
return instance;
}
}
泛型模式
public class Unitysingleton<T> : MonoBehaviour where T :Component
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType(typeof(T)) as T;
if (instance == null)
{
GameObject obj = new GameObject();
instance = obj.AddComponent<T>();
}
}
return instance;
}
}