知识点
知识点 | 作用 | 代码 |
泛型、单例模式(静态关键字) | 减少单例模式重复代码的书写 | BaseManager |
单例模式基类模块
一、非泛型
public class GameManager
{
private static GameManager instance;
public static GameManager GetInstance()
{
if(instance == null)
instance = new GameManager();
return instance;
}
}
由于游戏中有几十个管理器都是单例模式,如果用上述方法就会出现大量的重复工作,十分浪费时间
二、泛型
public class BaseManager<T> where T : new()
{
private static T instance;
public static T GetInstance(){
if(instance == null)
instance = new T();
return instance;
}
}
//GameManager继承BaseManager
public class GameManager : BaseManager<GameManager>()
{
}
多线程可能会用到双锁
继承MonoBehaviour的单例模式基类
一、非泛型
public class NewBehaviourScript : MonoBehaviour
{
public static NewBehaviourScript instance;
public static NewBehaviourScript GetInstance()
{
//继承了Mono脚本不能直接new
//只能通过拖动到对象物体上 或者 加脚本的api AddComponent去加脚本
//U3D内部帮助我们实例化它
return instance;
}
void Awake()
{
instance = this;
}
}
二、泛型
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
//继承了Mono脚本不能直接new
//只能通过拖动到对象物体上 或者 加脚本的api AddComponent去加脚本
//U3D内部帮助我们实例化它
return instance;
}
protected virtual void Awake(){
instance = this as T;
}
}
继承了 MonoBehaviour 的单例模式对象 需要我们自己保证它的唯一性。
单例模式对象往往出现在程序的整个生命周期
继承这种自动创建的 单例模式基类 不需要手动去拖 或者 api去加了
public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
if(instance == null)
{
GameObject obj = new GameObject();
//设置对象的名字为脚本名
obj.name = typeof(T).ToString();
instance = obj.AddComponent<T>();
}
return instance;
}
}