c# - MissingReferenceException 没有意义

标签 c# unity-game-engine

我收到 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 the GameObject or any of its children.

此外,shipParentTransform 很可能是第一个被发现并摧毁的!因此,在下一次迭代中,所有子 obj 也已被标记为已销毁。


相反,你应该使用

foreach (Transform obj in shipParent.transform)
{
    Destroy(obj.gameObject);
}

这个 Transform 类型的内置枚举迭代器完全符合您的预期:返回所有第一级子级的 Transform 引用。

关于c# - MissingReferenceException 没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607172/

相关文章:

c# - 在遗留 tcp IP 服务器和 WCF 应用程序之间进行通信

c# - UWP:如果指针被按下,则指针移动

c# - MySQL 数据库未显示在数据源中

c# - 调用 Texture2D.readPixels 时 iOS 挂起

c# - 在 Unity Inspector 窗口中获取选定的组件

android - Facebook SDK for Unity on Android - 关于 FB.Login 回调的问题

c# - 3个带linq的嵌套组

c# - Lazy<T> 和 LazyInit<T> 之间的区别

ios - Facebook登录统一iOS游戏而无需重定向

c# - OnCollisionEnter2D 和 OnCollisionExit2D 的问题