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。