MissingReferenceException:精灵 'ui_button_bg' 已被销毁,但你仍在尝试访问它。你的脚本应检查它是否为空,或者你不应销毁该对象。
MissingReferenceException: The sprite 'ui_button_bg' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
ID: unity/missingreferenceexception-ui-image-sprite
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Unity 2022.3.18f1 | active | — | — | — |
| Unity 2023.1.5f1 | active | — | — | — |
| Unity 2021.3.33f1 | active | — | — | — |
根因分析
UI Image 组件的精灵引用指向了一个已被销毁的 Sprite 对象(例如通过 Resources.UnloadUnusedAssets 或场景卸载),而 Image 仍然存在。
English
A UI Image component's sprite reference points to a Sprite object that was destroyed (e.g., via Resources.UnloadUnusedAssets or scene unloading) while the Image still exists.
官方文档
https://docs.unity3d.com/ScriptReference/MissingReferenceException.html解决方案
-
Before accessing the sprite, check if the Image component's sprite is null and reassign it from a persistent source (e.g., Resources.Load or Addressables).
-
Ensure the sprite asset is marked as 'Keep' in the Addressables system or is included in a preloaded asset bundle to prevent it from being unloaded.
无效尝试
常见但无效的做法:
-
70% 失败
The sprite reference is lost at runtime due to destruction, not because it was never assigned. Setting null prevents the error but breaks UI functionality.
-
95% 失败
This actually causes the problem; it destroys sprites that are still referenced.
-
90% 失败
Sprites are not GameObjects; DontDestroyOnLoad works on GameObjects, not assets.