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

    }
}

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

相关推荐
程序猿多布6 小时前
预定义委托(C# and Unity)
unity·c#
It_BeeCoder10 小时前
Java:单例模式(Singleton Pattern)及实现方式
java·单例模式·程序员
S-X-S10 小时前
八种单例模式详解
单例模式
Edision_li15 小时前
DeepSeek教unity------Dotween
unity·游戏引擎
zfoo-framework17 小时前
Unity中NavMesh的使用 及其 导出给java服务端进行寻路
unity
程序猿多布17 小时前
数学函数(C#、Lua 、Unity)
unity·c#·lua
TheFirst00818 小时前
The First项目报告:重塑链上游戏生态,解读B3 Base的双赢局面
游戏
爱写代码的山山1 天前
虚幻蓝图解决抗锯齿方案
游戏·ue5·游戏引擎·虚幻·抗锯齿化
卷福同学1 天前
设计模式2:单例模式
java·单例模式·设计模式
道友老李1 天前
【设计模式精讲】创建型模式之单例模式(饿汉式、懒汉式、双重校验、静态内部类、枚举)
单例模式·设计模式