You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity报错:WeaponManager对象已销毁仍被访问,脚本无法引用求助

Unity MissingReferenceException 解决思路(WeaponManager 实例被销毁问题)

排查 DontDestroyOnLoad 的正确使用

  • 确保调用时机:必须在对象被销毁前调用 DontDestroyOnLoad,通常放在 Awake() 或 Start() 中,同时避免将该对象设为场景临时对象(比如动态生成后未妥善处理的实例)
  • 处理重复实例:场景切换时若新场景存在同名WeaponManager,会导致原DontDestroyOnLoad实例被意外销毁,可通过单例逻辑规避:
    private static WeaponManager _instance;
    void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }
        _instance = this;
        DontDestroyOnLoad(gameObject);
    }
    

定位对象销毁的触发源

  • 全局搜索 Destroy(WeaponManager) 或WeaponManager脚本内的 Destroy(gameObject),排查是否存在主动销毁的逻辑错误
  • 检查场景卸载逻辑:若使用 SceneManager.UnloadSceneAsync,确认WeaponManager所在场景未被误卸载(DontDestroyOnLoad实例属于独立场景,不会被普通场景卸载影响,但手动移至待卸载场景会失效)
  • 排查其他脚本的误操作:检查UI、状态管理等脚本是否引用并销毁了WeaponManager实例

规范空值检查逻辑

  • 每次访问WeaponManager成员前必须做空值判断:
    if (WeaponManager.Instance != null)
    {
        WeaponManager.Instance.EquipWeapon();
    }
    
  • 静态引用需手动清空:静态变量不会随对象销毁自动置空,需在 OnDestroy 中处理:
    void OnDestroy()
    {
        if (_instance == this)
        {
            _instance = null;
        }
    }
    

额外排查点

  • 检查动态生成逻辑:若通过 Instantiate 创建WeaponManager,需确保生成后立即调用 DontDestroyOnLoad,避免场景切换时被销毁
  • 编辑器面板验证:场景切换后查看Hierarchy面板顶部的DontDestroyOnLoad分组,确认实例是否存在;若不存在,说明 DontDestroyOnLoad 的调用逻辑未执行

内容的提问来源于stack exchange,提问作者Gyuyeong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 00:55:13