UnassignedReferenceException 即使使用空条件运算符 [英] UnassignedReferenceException even though using the null-conditional operator

查看:32
本文介绍了UnassignedReferenceException 即使使用空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个 UnassignedReferenceException: The variable _Preset of Foo has not beenassigned. 即使我使用的是 空条件运算符 ?..

I'm getting a UnassignedReferenceException: The variable _Preset of Foo has not been assigned. even though I'm using the null-conditional operator ?..

我的代码:

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

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

I'm also noticing that it mentions _Preset instead of Preset (which I find odd).

Foo.cs 中的代码:

Code in Foo.cs :

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

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

我做错了什么?这不就是运营商的作用吗?

What am I doing wrong? Isn't it what the operator is for?

谷歌搜索没有帮助.

推荐答案

Unity 有一种自定义方法来检查检查器的引用是否为空.

当 MonoBehaviour 有字段时,仅在编辑器中[1],我们不会将这些字段设置为真正的空",而是设置为假空"对象.我们的自定义 == 运算符能够检查某物是否是这些假空对象之一,并相应地进行操作

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

他们可能没有重载空条件运算符.您的 get 属性返回解释未分配错误的假空值"(而不是 NullReferenceException).

They may not have overloaded the null-conditional operator. Your get property returns the "fake null" explaining your unassigned error (and not the NullReferenceException).

自定义空检查也有很多缺点.它的行为与 ??运算符,它也执行空检查,但该运算符执行纯 c# 空检查,并且无法绕过调用我们的自定义空检查.

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.

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

I guess the same problem occurs for the null-conditional operator.

这篇关于UnassignedReferenceException 即使使用空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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