如何在 Unity 中的可为空上下文中初始化引用类型类属性?

jai*_*p89 5 c# unity-game-engine

由于您应该使用Start()orAwake()方法而不是 Unity 中的类构造函数来初始化类属性,因此 VisualStudio 会抱怨,如果您处于可为 null 的上下文中,则在退出构造函数时引用类型必须具有非 null 值:

#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();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将所有引用类型属性设置为可为空,但这会迫使您每次取消引用属性时都检查是否为空,即使在方法中初始化它之后也是如此Start()

Unity 有正确的处理方法吗?

小智 2

使用容空运算符“!”。像这样:

private GameObject something = null!;
Run Code Online (Sandbox Code Playgroud)