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

    }
}

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

相关推荐
白太岁3 小时前
C++:(5) 单例模式与支持初始化失败的单例模式
c++·单例模式
程序猿零零漆7 小时前
【Spring Boot开发实战手册】掌握Springboot开发技巧和窍门(六)创建菜单和游戏界面(下)
java·spring boot·游戏
月下雨(Moonlit Rain)8 小时前
宇宙飞船游戏项目
python·游戏·pygame
海天一色y8 小时前
使用 Python + Tkinter 打造“猫狗大战“回合制策略游戏
开发语言·python·游戏
淡海水21 小时前
【节点】[EvaluateSimulationAdditionalData节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·simulation·evaluate
A懿轩A1 天前
【Java 基础编程】Java 面向对象进阶:static/final、抽象类、接口、单例模式
java·开发语言·单例模式
新缸中之脑1 天前
Tripo AI:构建游戏就绪的3D资产
人工智能·游戏·3d
小贺儿开发1 天前
Unity3D 文物互动大屏
3d·unity·实时互动·udp·socket·网络通信
秦奈1 天前
Unity学习复习随笔(12):网络开发基础
网络·笔记·学习·unity
郝学胜-神的一滴1 天前
单例模式:从经典实现到Vibe Coding时代的思考
开发语言·c++·程序人生·单例模式·设计模式·多线程