USP0016 Initialization detection with nullable reference types

March 2, 2022 ยท View on GitHub

C# 8.0 introduces nullable reference types and non-nullable reference types. Initialization detection needs to take Unity initialization methods into account.

Suppressed Diagnostic ID

CS8618 - Non-nullable field is uninitialized. Consider declaring the field as nullable.

Examples of code that produces a suppressed diagnostic

#nullable enable

using UnityEngine;

public class Test : Monobehaviour
{
	private GameObject field;
	
	private void Start()
	{
		Initialize();
	}
	
	private void Initialize()
	{
		field = new GameObject();
	}
}

and:

#nullable enable

using UnityEngine;

public class Test : Monobehaviour
{
	public GameObject Property { get; set; }
	
	private void Awake()
	{
		Property = GameObject.Find("Player");
	}
}

and:

#nullable enable

using UnityEngine;

public class Test : Monobehaviour
{
	[SerializeField] private UnityEngine.Object serializedField;
}

Why is the diagnostic reported?

The Code Style analyzer cannot detect that specific members are initialized by the Unity runtime.

Why do we suppress this diagnostic?

Fields or properties can be assigned to in Unity's initialization methods such as OnEnable(), Awake(), and Start() or all methods called by these, or the inspector.