UnassignedReferenceException even though using the null-conditional operator

前端 未结 2 2052
梦如初夏
梦如初夏 2020-12-07 04:18

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

相关标签:
2条回答
  • 2020-12-07 04:40

    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.

    0 讨论(0)
  • 2020-12-07 04:58

    As a late update and if you have the possibility to, you should definitely use the ReSharper Extension for Unity.

    Among other neat features, whenever it can, ReShaper for Unity will warn you if you are trying to use an operator you shouldn't on an Unity object.

    0 讨论(0)
提交回复
热议问题