我收到 MissingReferenceException
但它没有意义,因为我正在销毁 GameObject
,但我再也没有在代码中提及它。
控制台中的整个错误:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Transform[] currentShips = shipParent.GetComponentsInChildren<Transform>();
if (currentShips.Length > 0)
{
foreach (Transform obj in currentShips)
{
Destroy(obj.gameObject);
}
}
这对我来说没有意义,因为没有其他对 currentShips
的引用(当然也没有对 obj
的引用,因为它是本地的)。我还尝试检查 if
语句中的 currentShips != null
,但没有任何变化。我猜这只是我忽略的一件简单的事情,但这就是这个网站的用途,对吗?
最佳答案
这里你得到的是Unity内置的特殊形式的NullReferenceException
,只是销毁Unity中的引用后实际上并不是null
,但仍然存储了一些信息例如为什么它是null
。
因此,检查 currentShips != null
不会执行任何操作,因为异常并非来自此处。它可能相当符合要求
Destroy(obj.gameObject);
其中obj
已经被破坏了!
Kay 的评论以及 Adriani6 删除的答案中已经提到了实际问题:
shipParent.GetComppnentsInChildren<Transform>()
包括 shipParent
对象本身的 Transform
组件!!
Returns all components of Type
type
in theGameObject
or any of its children.
此外,shipParent
的 Transform
很可能是第一个被发现并摧毁的!因此,在下一次迭代中,所有子 obj
也已被标记为已销毁。
相反,你应该使用
foreach (Transform obj in shipParent.transform)
{
Destroy(obj.gameObject);
}
这个 Transform
类型的内置枚举迭代器完全符合您的预期:返回所有第一级子级的 Transform
引用。
关于c# - MissingReferenceException 没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607172/