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

    }
}

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

相关推荐
Jason?132 小时前
Unity基于Recoder的API写了一个随时录屏的工具
java·unity·游戏引擎
年少无知且疯狂4 小时前
【Unity】RectTransformUtility.ScreenPointToLocalPointInRectangle
unity·游戏引擎
weixin_424294678 小时前
Unity 调节 Rigidbody2D 响应速度的解决方案【资料】
unity·游戏引擎
霜绛8 小时前
Unity笔记(三)——父子关系、坐标转换、Input、屏幕
笔记·学习·unity·游戏引擎
2501_917970039 小时前
主播生活模拟器2|主播人生模拟器2 (Streamer Life Simulator 2)免安装中文版
java·游戏·生活
AI创世纪11 小时前
微软XBOX游戏部门大裁员
游戏·microsoft·xbox
zxc2446039341 天前
gpu instancer crowd 使用自定义材质并且只修改单个物体的材质参数
unity·材质
YF云飞1 天前
游戏行业DDoS攻防实战指南
游戏·ddos
伽蓝_游戏1 天前
UGUI源码剖析(3):布局的“原子”——RectTransform的核心数据模型与几何学
ui·unity·架构·c#·游戏引擎·游戏程序·几何学
Kingsdesigner1 天前
游戏开发流程革命:我用Substance插件,在UE5内实现材质的实时“创世纪”
游戏·adobe·ue5·游戏引擎·游戏开发·设计师·substance 3d