'How do you initialize reference type class properties in a nullable context in Unity?

As you are supposed to use the Start() or Awake() methods instead of the class constructors in Unity to initialize your class properties, VisualStudio complains that the reference types must have a non-null value when exiting the constructor if you are within a nullable context:

#nullable enable
using UnityEngine;

public class NullableTest : MonoBehaviour
{
    // Non-nullable field 'something' must contain a non-null value when exiting
    // constructor. Consider declaring the field as nullable:
    private GameObject something;

    void Start()
    {
        something = new GameObject();
    }
}

You could set all your reference typed properties to nullable, but that would force you to check for null every time you dereference a property even after you initialized it in the Start() method.

Is there a correct way of handling this in Unity?



Solution 1:[1]

Use the null-forgiving operator "!". Just like this:

private GameObject something = null!;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ktxiaok