Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
来源:互联网 发布:linux域名绑定公网ip 编辑:程序博客网 时间:2024/05/24 15:40
上一篇文章讲述了如何设计C#单例的模板。也随之抛出了问题:
如何设计接收MonoBehaviour生命周期的单例的模板?
如何设计?
先分析下需求:
1.约束脚本实例对象的个数。
2.约束GameObject的个数。
3.接收MonoBehaviour生命周期。
4.销毁单例和对应的GameObject。
首先,第一点,约束脚本实例对象的个数,这个在上一篇中已经实现了。
但是第二点,约束GameObject的个数,这个需求,还没有思路,只好在游戏运行时判断有多少个GameObject已经挂上了该脚本,然后如果个数大于1抛出错误即可。
第三点,通过继承MonoBehaviour实现,只要覆写相应的回调方法即可。 第四点,在脚本销毁时,把静态实例置空。 完整的代码就如下所示:
using UnityEngine;/// <summary>/// 需要使用Unity生命周期的单例模式/// </summary>namespace QFramework { public abstract class QMonoSingleton<T> : MonoBehaviour where T : QMonoSingleton<T> { protected static T instance = null; public static T Instance() { if (instance == null) { instance = FindObjectOfType<T>(); if (FindObjectsOfType<T>().Length > 1) { QPrint.FrameworkError ("More than 1!"); return instance; } if (instance == null) { string instanceName = typeof(T).Name; QPrint.FrameworkLog ("Instance Name: " + instanceName); GameObject instanceGO = GameObject.Find(instanceName); if (instanceGO == null) instanceGO = new GameObject(instanceName); instance = instanceGO.AddComponent<T>(); DontDestroyOnLoad(instanceGO); //保证实例不会被释放 QPrint.FrameworkLog ("Add New Singleton " + instance.name + " in Game!"); } else { QPrint.FrameworkLog ("Already exist: " + instance.name); } } return instance; } protected virtual void OnDestroy() { instance = null; } }}
总结:
目前已经实现了两种单例的模板,一种是需要接收Unity的生命周期的,一种是不需要接收生命周期的,可以配合着使用。虽然不是本人实现的,但是用起来可是超级爽快,2333。
阅读全文
0 0
- Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
- Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
- Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
- Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
- Unity 游戏框架搭建 (二) 单例的模板
- Unity 游戏框架搭建 (二) 单例的模板
- Unity 游戏框架搭建 (二) 单例的模板
- Unity 游戏框架搭建 (十三) 无需继承的单例的模板
- Unity 游戏框架搭建 (十三) 无需继承的单例的模板
- Unity 游戏框架搭建 (十三) 无需继承的单例的模板
- Unity继承MonoBehaviour的静态单例
- 【Unity】非MonoBehaviour子类的单例管理
- MonoBehaviour的单例模式
- MonoBehaviour的单例模式
- UNITY 单例模式的模板
- C#单例与继承MonoBehaviour的单例
- Unity中Monobehaviour的生命周期
- Unity 游戏框架搭建 (十四) 优雅的QSignleton(零) QuickStart
- Winform中的dataGridView添加自动编号
- Unity 游戏框架搭建 (二) 单例的模板
- 找到一本不错的Linux电子书,附《Linux就该这么学》章节目录。
- Mysql-python安装
- 关于“声明提升”
- Unity 游戏框架搭建 (三) MonoBehaviour单例的模板
- 『ORACLE』外部表external table创建(11g)
- 搜索 L
- postgresql日期相关的截取和计算
- Keil uVision5 下载程序 add flash programming algorithm选项缺少需要的算法解决办法
- epoll et模式
- Linux常用命令
- Unity 游戏框架搭建 (四) 简易有限状态机
- 随机数