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

相关推荐
布莱克6054 小时前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
是main不是漫4 小时前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法
布莱克6056 小时前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
Risehuxyc8 小时前
PHP能不能在参数里放匿名函数
开发语言·php
码云社区8 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
FRing038 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
whitelbwwww10 小时前
CUDA C++实战--中级
开发语言·前端·c++
FungLeo10 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
谙弆悕博士12 小时前
多智能体架构详解:市场拍卖式架构(Market-based / 竞价协商)
开发语言·架构·去中心化·多智能体·智能体·拍卖架构
ShineWinsu12 小时前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框