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);
        }

    }
}

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

相关推荐
evolution_language1 小时前
Unity场景(Scene)的注意事项和易错点
unity·游戏引擎·scene
U***e631 小时前
元宇宙在虚拟现实游戏中的交互设计
游戏·vr
远程软件小帮手3 小时前
UU远程上线mac被控!如何远程控制 macOS 设备办公?
游戏·macos·智能手机·电脑
EQ-雪梨蛋花汤4 小时前
【AI工具】使用 Doubao-Seed-Code 优化 Unity 编辑器插件:从功能实现到界面美化的完整实践
人工智能·unity·编辑器
熊猫钓鱼>_>5 小时前
从零开始构建RPG游戏战斗系统:实战心得与技术要点
开发语言·人工智能·经验分享·python·游戏·ai·qoder
Dr.勿忘8 小时前
开源Unity小框架:高效单例与模块化设计
游戏·unity·开源·c#·游戏引擎·游戏程序·gamejam
wheeldown9 小时前
【Linux】多线程核心速记:线程池 + 单例模式 + 线程安全 + 死锁 + 智能指针
linux·运维·服务器·安全·单例模式
zstar-_1 天前
我用AI做了一个3D六子棋游戏
人工智能·游戏
悦悦欧呐呐呐呐1 天前
休闲摸鱼小游戏扫雷游戏|下载即玩
游戏
wanhengidc2 天前
云手机是由什么组成的?
运维·服务器·web安全·游戏·智能手机