赞
踩
在Unity程序中我们利用单例模式的类保证内存里只有一个实例,减少了内存的开销,可以避免对资源的多重占用,单例模式设置全局访问点,可以优化和共享资源的访问。
//1.C#中 泛型的知识
//2.设计模式中 单例模式的知识
public class BaseManager<T> where T:new()
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
instance = new T();
return instance;
}
}
//C#中 泛型知识点
//设计模式 单例模式的知识点
//继承了 MonoBehaviour 的 单例模式对象 需要我们自己保证它的唯一性
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;
}
}
继承此类的脚本,若在多处游戏对象中使用时,挂载此对象的最后一个起作用!
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();
//让这个单例模式对象 过场景 不移除
//因为 单例模式对象 往往 是存在整个程序生命周期中的
DontDestroyOnLoad(obj);
instance = obj.AddComponent<T>();
}
return instance;
}
}
继承此类的脚本,过场景不移除,这个基类不需要手动添加或者在脚本里进行添加,想用它直接 GetInstance就行。
BaseManager
基类。NewBehaviourScript
增加一个测试方法。public class NewBehaviourScript : BaseManager<NewBehaviourScript>
{
public void testOut() {
Debug.Log("测试输出!");
}
}
BaseTest
脚本。通过NewBehaviourScript
提供的GetInstance
来调用测试方法。
public class BaseTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
NewBehaviourScript.GetInstance().testOut();
}
}
BaseTest
脚本到Main Camera
运行结果。SingletonMono
基类。BaseTest
脚本继承SingletonMono
基类。public class BaseTest : SingletonMono<BaseTest>
{
// Start is called before the first frame update
void Start()
{
Debug.Log(BaseTest.GetInstance().name);
}
}
BaseTest
到Main Camera
运行结果。SingletonAutoMono
基类。public class BaseTest : SingletonAutoMono<BaseTest>
{
// Start is called before the first frame update
void Start()
{
Debug.Log(BaseTest.GetInstance().name);
}
}
为什么会有两次输出,思考一下!
链接:
Unity程序开发框架——单例模式基类模块.
Unity程序开发框架——缓存池模块.
Unity程序开发框架——事件中心模块.
Unity程序开发框架——公共Mono模块.
Unity程序开发框架——场景切换模块.
Unity程序开发框架——资源加载模块.
Unity程序开发框架——输入控制模块.
Unity程序开发框架——UI管理模块.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。