C# 8.0
introduces nullable reference types
and non-nullable reference types
. Initialization detection needs to take Unity initialization methods into account.
CS8618 - Non-nullable field is uninitialized. Consider declaring the field as nullable.
#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;
}
The Code Style analyzer cannot detect that specific members are initialized by the Unity runtime.
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.