jaimecp89
jaimecp89

Reputation: 53

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?

Upvotes: 5

Views: 612

Answers (1)

ktxiaok
ktxiaok

Reputation: 44

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

private GameObject something = null!;

Upvotes: 2

Related Questions