Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c# - UnassignedReferenceException even though using the null-conditional operator

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

My code:

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

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

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?

Google searches didn't help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

They may not have overloaded the null-conditional operator. Your get property returns the "fake null" explaining your unassigned error (and not the 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...