c# - "var g = myComponent?.gameObject"给出错误,但 "var g = myComponent == null ? null : myComponent.gameObject"没有

标签 c# unity-game-engine

正如标题所说,我有一个局部变量,我们可以将其称为 myComponent这是单一行为的一种。嗯,确实是myOtherComponent.myComponent ,但是myOtherComponent Start() 之后从未改变所以我不明白它如何改变任何东西,特别是因为以下是我对代码进行的唯一更改:

var g = myComponent?.gameObject;
if(g != null) {  /* sometimes does: */  Destroy(myComponent); }
else {  /* sometimes does: */  myComponent = Instantiate(); }

“MissingReferenceException:‘BlockPreview’类型的对象已被销毁,但您仍在尝试访问它。 您的脚本应该检查它是否为空,或者您不应该销毁该对象。 [然后有一个直接链接到var g线。]”

但是当我将该代码更改为:

var g = myComponent == null ? null : myComponent.gameObject;
if(g != null) {  /* sometimes does: */  Destroy(myComponent); }
else {  /* sometimes does: */  myComponent = Instantiate(); }

没有错误。它工作得很好。

但据我所知(刚刚用谷歌搜索),那么 myComponent?.gameObject实际上只是 myComponent == null ? null : myComponent.gameObject 的简写.

我知道我可以写得更好,比如替换 myOtherComponent 中的变量来自MyComponent输入 GameObject例如,我想知道为什么会发生这种情况,以避免将来发生这种情况。虽然,这看起来像是 Unity 中的一个错误,但我不知道。

最佳答案

Unity官方支持响应

UnityEngine.Object and those who inherit it, do not support null conditional operator. The Docs are updated to reflect this

https://issuetracker.unity3d.com/issues/c-number-6-null-conditional-access-operator-dot-throws-missingcomponentexception-instead-of-recognizing-as-null

关于c# - "var g = myComponent?.gameObject"给出错误,但 "var g = myComponent == null ? null : myComponent.gameObject"没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065049/

相关文章:

android - 即使有 Intent 过滤器,我的应用程序在共享对话框中也不可见

c# - 3d 鼠标瞄准相机第三人称垂直 C#

android - Unity3d 为多屏幕尺寸设计游戏

c# - 具有相同 xaml 文件和不同 DataContext 的多个输入表单

c# - 编码 C 和 C#

c# - Xamarin。恢复后的不同行为应用程序

c# - xaml中的菜单栏如何自行调整大小?

javascript - 如何使用AddForce功能?这是行不通的

android - 无法在 play-games-plugin-for-unity 中加载库 libgpg.so

c# - Entity Framework 6 : audit/track changes