Unity游戏通用框架——单例模式

Unity的单例可以分为两类,一类单例是C#中的纯单例,用于进行数据的管理(例如角色类管理器,房间类管理器,数据管理器等)。一类是基础与Unity的MonoBehavior的单例,用于跟Unity相关组件的游戏管理(例如声音管理器,游戏管理器,场景管理器等)

第一类:

csharp 复制代码
public class Singleton<T> where T : new()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }
}

第二类:

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Assets.Script.Base
{
    public abstract class MonoSingleton<T> :MonoBehaviour where T : MonoBehaviour
    {
        public bool global = true;
        static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance =(T)FindObjectOfType<T>();
                }
                return instance;
            }

        }

        void Awake()
        {
            if (global)
            {
                if (instance != null && instance!=this.gameObject.GetComponent<T>())//判断单例不为空且不是当前单例则销毁此次单例
                {
                    Destroy(this.gameObject);
                    return;
                }
                DontDestroyOnLoad(this.gameObject);//不消毁
                instance = this.gameObject.GetComponent<T>();
            }
            this.OnStart();
        }

        protected virtual void OnStart()
        {

        }

        public void Destroy_this()
        {
            Destroy(this.gameObject);
        }

    }
}

用法:根据用法直接继承上面两个类的其中一个即可

相关推荐
Axis tech2 小时前
Xsens虚拟动作捕捉技术在影视、游戏、动画中的应用
游戏
世洋Blog2 小时前
H5游戏-Canvas绘制与JS基础
javascript·游戏·h5·canvas
jtymyxmz4 小时前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
前端不太难4 小时前
HarmonyOS 游戏里的“假异步”,为什么会卡
游戏·状态模式·harmonyos
子春一5 小时前
Flutter for OpenHarmony:构建一个沉浸式 Flutter 掷骰子游戏,深入解析动画控制器、CustomPaint 自定义绘制与状态同步
flutter·游戏
天人合一peng5 小时前
unity获得和修改button的text(TMP)
java·前端·unity
dzj202113 小时前
Unity中使用LLMUnity遇到的问题(三)——如何配置和使用知识库
unity·llmunity·知识库大模型
Elastic 中国社区官方博客13 小时前
使用 Discord 和 Elastic Agent Builder A2A 构建游戏社区支持机器人
人工智能·elasticsearch·游戏·搜索引擎·ai·机器人·全文检索
Clank的游戏栈14 小时前
Unity自动化美术资源校验工具(模型/材质规范检测)技术详解
unity·自动化·材质
钦拆大仁16 小时前
Java设计模式-单例模式
java·单例模式·设计模式