调用Destroy方法导致GameObject变量source_prefab赋值失败问题
问题分析与解决方案
你遇到的核心问题是:source_prefab在调用Destroy(_item.gameObject)后变为null,但其他变量(如item_name、item_icon等)能正常保留。原因在于source_prefab如果引用的是场景中实例化的游戏对象,销毁该场景对象后,对应的引用会直接失效;而其他变量要么是值类型(如int、bool),要么引用的是Project面板中的资源文件(如Sprite),不受场景对象销毁的影响。
以下是几种无需延迟销毁的解决方案:
方案1:手动指定source_prefab为原始预制体
直接在Unity编辑器中,将item组件的source_prefab字段拖拽Project面板里的原始预制体,而非场景中的物品实例。这样source_prefab引用的是资源文件,即使销毁场景中的物品对象,引用也不会变为null。
方案2:代码自动关联原始预制体
如果不想手动设置source_prefab,可以在item脚本中添加逻辑,自动获取当前对象对应的原始预制体:
using UnityEngine; #if UNITY_EDITOR using UnityEditor; // 仅在编辑器模式生效,发布时会自动剔除 #endif public class item : MonoBehaviour { public int quantity; public bool stackable; public string item_name; [TextArea] public string item_description; public Sprite item_icon; public GameObject source_prefab; private void Awake() { #if UNITY_EDITOR // 自动获取当前对象对应的原始预制体 source_prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject); #endif } }
这样即使source_prefab未手动赋值,也会自动关联到原始预制体,销毁场景实例后引用依然有效。
方案3:在AddItem中兼容场景实例与预制体
如果需要兼容source_prefab既可能是场景实例也可能是预制体的情况,可以在赋值时自动转换为有效的预制体引用:
public void AddItem( item _item ) { itemInstance new_item = new itemInstance(); #if UNITY_EDITOR // 优先获取原始预制体,若本身就是预制体则直接使用 var validPrefab = PrefabUtility.GetCorrespondingObjectFromSource(_item.source_prefab) ?? _item.source_prefab; new_item.source_prefab = validPrefab; #else // 发布环境下直接使用传入的引用(确保此时source_prefab已正确关联预制体) new_item.source_prefab = _item.source_prefab; #endif new_item.quantity = _item.quantity; new_item.item_name = _item.item_name; new_item.item_description = _item.item_description; new_item.stackable = _item.stackable; new_item.item_icon = _item.item_icon; inventory.Add(new_item); UpdateInventory(); Destroy(_item.gameObject); }
内容的提问来源于stack exchange,提问作者hamdi
相关产品推荐
相关产品推荐

