UnassignedReferenceException 即使使用 null 条件运算符

UnassignedReferenceException even though using the null-conditional operator

尽管我使用的是 null-conditional operator ?.,但我得到了 UnassignedReferenceException: The variable _Preset of Foo has not been assigned.

我的代码:

// […]
myTarget.Preset?.ApplyTo(myTarget);

我还注意到它提到了 _Preset 而不是 Preset(我觉得这很奇怪)。

Foo.cs中的代码:

[CreateAssetMenu()]
public class Foo : ScriptableObject
{
    [SerializeField] private Preset _Preset = null;

    public Preset Preset
    {
        get { return _Preset; }
        protected set { _Preset = value; }
    }
}

我做错了什么?算子不就是干这个的吗?

Google 搜索没有帮助。

Unity has a custom way to check inspector's references against null.

When a MonoBehaviour has fields, in the editor only[1], we do not set those fields to “real null”, but to a “fake null” object. Our custom == operator is able to check if something is one of these fake null objects, and behaves accordingly

他们可能没有重载 null 条件运算符。您的 get 属性 returns "fake null" 解释了您未分配的错误(而不是 NullReferenceException)。

The custom null check also comes with a bunch of downsides. It behaves inconsistently with the ?? operator, which also does a null check, but that one does a pure c# null check, and cannot be bypassed to call our custom null check.

我想空条件运算符也会出现同样的问题。

作为后期更新,如果有可能,您绝对应该使用 ReSharper Extension for Unity

除了其他简洁的功能外,ReShaper for Unity 会在您尝试使用不应该在 Unity 对象上使用的运算符时向您发出警告。