Why does C# null-conditional operator not work with Unity serializable variables?

▼魔方 西西 提交于 2020-12-26 07:12:11

问题


I've noticed that if I have some variables exposed to the Unity inspector such as:

[SerializeField] GameObject _tickIcon;

If I leave them unassigned and try to use the null conditional operator and call a method on that object I get an exception saying the variable is not assigned. So basically instead of doing this:

_tickIcon?.SetActive(false);

It's forcing me to do this:

if(_tickIcon != null)
{
   _tickIcon.SetActive(false)
}

So I'm guessing this must be something specific to unity's runtime, it's not really null, but I can check for null and it work. I don't really understand this.


回答1:


It does not work in general with anything inheriting from UnityEngine.Object!

It is bypassed due to how they internally implemented the ==/!= method differently. See Custom == operator, should we keep it?

ReSharper explained it pretty well in Possible unintended bypass of lifetime check of underlying Unity engine object

Object is in some occasions not really null but still keeps some meta data.

E.g. after

Destroy(_tickIcon);
_tickIcon.SetActive(false);

you will note that you don't get a normal NullReferenceException which would be the case if it were actually null but rather get a Unity customs MissingReferenceException telling you a probable reason for why the exception was thrown.


As solution UnityEngine.Object has the implicit bool operator

Does the object exist?

The example given there is actually not really true - see above

You should always check the existence of anything derived from UnityEngine.Object like this:

if(_tickIcon)
{
    _tickIcon.SetActive(false);
}


来源:https://stackoverflow.com/questions/62678228/why-does-c-sharp-null-conditional-operator-not-work-with-unity-serializable-vari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!