销毁对象后清空List抛出异常的技术解决方案咨询
问题分析与解决方案
报错原因
你的myObj是public字段,默认会被Unity自动序列化。当你销毁List中引用的GameObject后,Unity的序列化系统仍在尝试访问这些已销毁对象的序列化属性(比如报错里的outline.Array.data[0]),导致抛出序列化相关异常。代码里的Clear()或重新实例化操作无法同步更新Unity的序列化缓存,所以无效。
解决方法
方法一:阻止Unity序列化List(推荐)
给myObj添加[System.NonSerialized]特性,让Unity不再追踪这个List的序列化状态,代码层面的修改就能正常生效:
public GameObject parent; [System.NonSerialized] public List<GameObject> myObj = new List<GameObject>(); // 现在不会被Unity序列化 void Start() { // 先清空List移除引用,再销毁对象 myObj.Clear(); foreach (Transform child in parent.transform) { Destroy(child.gameObject); } // 可选:重新实例化List myObj = new List<GameObject>(); }
方法二:编辑器模式下强制刷新序列化状态(仅适用于编辑器)
如果需要在Inspector中保留List的可编辑性,可在销毁对象并清空List后,强制Unity刷新序列化缓存(仅编辑器环境有效):
using UnityEditor; public GameObject parent; public List<GameObject> myObj = new List<GameObject>(); void Start() { // 先清空List myObj.Clear(); // 编辑器下用DestroyImmediate销毁对象 foreach (Transform child in parent.transform) { DestroyImmediate(child.gameObject); } // 强制刷新序列化状态 EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); }
注意:DestroyImmediate和EditorUtility.SetDirty仅能在Unity编辑器中使用,发布版本无法运行,所以运行时场景优先用方法一。
内容的提问来源于stack exchange,提问作者Yidi
相关产品推荐
相关产品推荐

