4.单例模式问题2:重复挂载

一、单例模式重复挂载问题

1. 重复挂载会破坏单例唯一性

MonoBehaviour 单例依附在 GameObject 上,因此可能出现多个相同单例组件。

二、禁止同一 GameObject 重复挂载

可以给单例基类添加:DisallowMultipleComponent(治标不治本)

例如:

复制代码
[DisallowMultipleComponent]
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
}

它不能解决不同 GameObject 之间的重复问题。

三、运行时检测重复单例

真正保证唯一性的逻辑应该放在 Awake() 中。

复制代码
protected virtual void Awake()
{
    if (instance != null && instance != this)
    {
        Destroy(gameObject);
        return;
    }
    instance = this as T;
    DontDestroyOnLoad(gameObject);
}

四、为什么判断 instance != this

已经存在实例,并且这个实例不是当前对象时,才属于重复对象。

五、Destroy(this) 与 Destroy(gameObject)

Destroy(this)它只销毁当前单例组件,GameObject 本身仍然存在。

Destroy(gameObject);直接删除整个重复对象:

复制代码
if (instance != null && instance != this)
{
    Destroy(gameObject);
    return;
}

六、完整的 MonoBehaviour 单例基类

可以将重复挂载处理直接封装进基类:

复制代码
using UnityEngine;

[DisallowMultipleComponent]
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
    private static T instance;
    public static T Instance => instance;
    protected virtual void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this as T;
        DontDestroyOnLoad(gameObject);
    }

    protected virtual void OnDestroy()
    {
        if (instance == this)
        {
            instance = null;
        }
    }
}

七、OnDestroy 清除 Instance

复制代码
protected virtual void OnDestroy()
{
    if (instance == this)
    {
        instance = null;
    }
}

作用:当前真正的单例被销毁时,同时清空静态引用。

让单例状态和实际对象生命周期保持一致。注意一定要判断:

复制代码
instance == this

避免重复对象销毁时把真正的单例引用清掉。

八、自动创建单例的重复问题

如果使用自动创建方式:

复制代码
if (instance == null)
{
    GameObject obj = new GameObject(typeof(T).Name);
    instance = obj.AddComponent<T>();
    DontDestroyOnLoad(obj);
}

核心规则:自动创建的单例就不要再手动放进场景。

九、单例重复挂载的处理方式

第一层DisallowMultipleComponent

第二层Awake 中判断 Instance

相关推荐
jimy117 分钟前
C++ 虚函数表:基类和派生类共用一张 vtable 吗?
开发语言·c++
爱吃提升26 分钟前
Dev-C++ 5.11 C++断点调试完整教程
开发语言·c++
夜晚回家32 分钟前
Python 原始字符串详解 | r 前缀到底让什么不再转义
开发语言·python
陈年老古董38 分钟前
PyQt5 入门指南:环境搭建、PyCharm 外部工具配置与登录界面实战
开发语言·qt·pycharm
看浪的路人41 分钟前
第7讲:大模型后端服务化——Go 实现高并发 LLM Proxy / Router / Fallback
开发语言·后端·golang
iCxhust1 小时前
Matlab求解发电机的极限切除角
开发语言·算法·matlab·电力系统
zhanghaha13141 小时前
Qt 类完整例程【逐词拆解 + 逐步骤执行保姆教程】
开发语言·qt
samble1 小时前
从零搭建灌装监控系统(十八):自定义控件,三色灯与状态指示
c#·wpf·mvvm·modbus·工业控制
code2cat2 小时前
Java进阶篇之AtomicReferenceFieldUpdater:用不可变快照替换整份状态
java·开发语言·cas
Nathan__272 小时前
PHP面试题——情景应用
开发语言·php