关于u3d:U3D游戏开发框架二单例模版

5次阅读

共计 1186 个字符,预计需要花费 3 分钟才能阅读完成。

一:目标

当设计一个 Manager 时候, 咱们心愿整个程序只有一个该 Manager 的对象实例,最先想到的实现办法是这样的

public class XXXManager
{
    private static XXXManager _instance = null;
    public static XXXManager Ins
    {
        get
        {if (_instance == null)
            {_instance = new XXXManager();
            }
            return _instance;
        }
    }
}

如果每一个管理器类都实现一遍以上的单例代码会造成代码的反复,所以咱们要想方法把反复的代码抽离进去 

二:解决的问题及长处

——解决了实现单例代码的反复问题
——动态创建空物体并挂载脚本,不须要手动创立物体和挂载脚本

三:应用办法

须要实现单例的类间接继承单例模版即可,有继承 MonoBehaviour 和不继承 MonoBehaviour 两种

public class GameMgr : MonoSingleton<GameMgr>
{ }
 
public class UIMgr : Singleton<UIMgr>
{}

四:代码实现

/// <summary>
/// 不继承 Mono 的单例模版
/// </summary>
public abstract class Singleton<T>
    where T : new()
{
    private static T _instance;
    public static T Ins
    {
        get
        {if (_instance == null)
            {_instance = new T();
                (_instance as Singleton<T>).Init();}
            return _instance;
        }
    }
 
    /// <summary>
    /// 子类初始化的一些操作
    /// </summary>
    protected virtual void Init()
    {}}
using UnityEngine;
 
/// <summary>
/// 继承 Mono 的单例模版
/// </summary>
public abstract class MonoSingleton<T> : MonoBehaviour
    where T : MonoSingleton<T>
{
    private static T _instance;
    public static T Ins
    {
        get
        {if (_instance == null)
            {
                GameObject go = null;
                T t = FindObjectOfType<T>();
                if (t == null)
                {go = new GameObject(typeof(T).Name);
                    _instance = go.AddComponent<T>();}
                else
                {
                    go = t.gameObject;
                    go.name = typeof(T).Name;
                    _instance = go.GetComponent<T>();}
 
                DontDestroyOnLoad(go);
            }
            return _instance;
        }
    }
}

图片起源:手游

正文完
 0