gpt4 book ai didi

c# - UnassignedReferenceException 即使使用 null 条件运算符

转载 作者:行者123 更新时间:2023-12-04 16:45:09 26 4
gpt4 key购买 nike

我得到一个 UnassignedReferenceException: The variable _Preset of Foo has not been assigned. 即使我使用的是 null-conditional operator ?.

我的代码:

// […]
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 属性返回“假空值”来解释您未分配的错误(而不是 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.

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

关于c# - UnassignedReferenceException 即使使用 null 条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com