设计模式——泛型单例类

游戏中很多管理类都需要写成单例类,每次重复把管理类设置为单例类很繁琐,

这里直接写一个泛型单例类作为模板父类,方便其他需要写成单例类的类直接继承设置为单例类;

cs 复制代码
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T:Singleton<T>
{
    private static T instance;

    public static T Instance
    {
        get { return instance; }
    }

    public static bool IsInitialized
    {
        get { return instance != null; }
    }

    protected virtual void Init()
    {
        if (instance != null) Destroy(gameObject);
        else instance = (T)this;
    }

    protected virtual void Destroy()
    {
        if (instance == this) instance = null;
    }
}

其他要写成单例类的类,可以直接继承Singleton,示例如下:

cs 复制代码
using UnityEngine;

public class GameManager : Singleton<GameManager>
{
    protected override void Init()
    {
        base.Init();
        if (IsInitialized) Debug.Log("游戏初始化!");
    }
}
相关推荐
Mh4 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊5 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3335 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx6 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥6 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
SmalBox7 天前
10-04-实战-资源组织与依赖管理实战
unity3d·游戏开发
用户624293196627 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊7 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread7 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶7 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式