为什么C#空条件运算符不能与Unity可序列化变量一起使用? [英] Why does C# null-conditional operator not work with Unity serializable variables?

查看:52
本文介绍了为什么C#空条件运算符不能与Unity可序列化变量一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我有一些变量暴露给Unity检查器,例如:

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

[SerializeField] GameObject _tickIcon;

如果我未分配它们,并尝试使用null条件运算符并对该对象调用方法,则会收到异常消息,说明未分配变量.因此,基本上不要这样做:

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);

这迫使我这样做:

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

所以我猜想这一定是unity的运行时特有的东西,它并不是真正的null,但是我可以检查null是否可以正常工作.我真的不太明白.

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.

推荐答案

它通常不适用于从由于他们在内部不同地实现 == /!= 方法的方式而被绕开.请参见自定义==运算符,如果我们保留它?

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

ReSharper在可能的,无意间忽略了基础Unity引擎对象的生命周期检查

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

对象在某些情况下不是真正的 null ,但仍保留一些元数据.

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

例如之后

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

您会注意到,您没有得到正常的 NullReferenceException ,而实际上却是 null ,而是获得了Unity习惯 MissingReferenceException 告诉您引发异常的可能原因.

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.

作为解决方案, UnityEngine.Object 具有隐式的 布尔运算符

As solution UnityEngine.Object has the implicit bool operator

对象是否存在?

给出的示例实际上并不是真的-见上文

您应该始终检查是否存在从 UnityEngine.Object 派生的任何东西,如下所示:

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

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

这篇关于为什么C#空条件运算符不能与Unity可序列化变量一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆