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

发布于:2024-10-12 ⋅ 阅读:(13) ⋅ 点赞:(0)

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

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

第二类:

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

    }
}

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