Unity万能单例框架

1.0 需要挂载游戏对象的单例类

 public abstract class SingletonBaseMono<T> : MonoBehaviour where T : SingletonBaseMono<T>
{
    protected static T _Instance = null;
    public static T Instance
    {
        get
        {
            if (null == _Instance)
            {
                //寻找是否存在当前单例类对象
                GameObject go = GameObject.Find(typeof(T).Name);
                //不存在的话
                if (go == null)
                {
                    //new一个并添加一个单例脚本
                    go = new GameObject();
                    _Instance = go.AddComponent<T>();
                }
                else
                {
                    if (go.GetComponent<T>() == null)
                    {
                        go.AddComponent<T>();
                    }
                    _Instance = go.GetComponent<T>();
                }
                //在切换场景的时候不要释放这个对象
                DontDestroyOnLoad(go);
            }
            return _Instance;
        }
    }
}               

2.0 数据类单例

public class SingletonBase<T> where T : class ,new()
{
    private static T _instance=null;

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }

    //构造的同时调用初始化函数
        protected SingletonBase()
        {
            if (null != _instance)
            Init();
        }

    public virtual void Init()
    {

    }
}
### Unity 中简模式实现 在 Unity 开发过程中,模式是一种常见的设计模式,用于确保某个类只有一个实存在,并提供全局访问点。下面是一个基本的模式实现方法: #### 使用静态属性和构造函数保护来创建 Singleton 类 ```csharp using UnityEngine; public class SimpleSingleton : MonoBehaviour { private static SimpleSingleton _instance; public static SimpleSingleton Instance { get { if (_instance == null) { _instance = FindObjectOfType<SimpleSingleton>(); if(_instance == null){ GameObject singletonObject = new GameObject(); _instance = singletonObject.AddComponent<SimpleSingleton>(); singletonObject.name = typeof(SimpleSingleton).ToString() + " (Singleton)"; } } return _instance; } } protected virtual void Awake() { if (_instance != this && _instance != null) { Destroy(gameObject); } else { _instance = this; DontDestroyOnLoad(this.gameObject); // 防止场景切换时销毁对象 } } } ``` 此代码片段展示了如何通过 `Awake` 方法检查当前场景中是否存在其他相同类型的组件实[^1]。如果已经有一个实,则销毁新创建的对象;如果没有找到任何现有实,则设置 `_instance` 并调用 `DontDestroyOnLoad()` 来防止该对象被卸载。 为了使这个子更加完善,在实际项目里还可以考虑加入更多功能,比如延迟初始化、线程安全等特性。不过对于大多数情况来说,上述实现方式已经足够满足需求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_阿松先生

感谢您的支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值