Home Setup Nullable reference type in Unity
Post
Cancel

Setup Nullable reference type in Unity

🎯 What is Nullable reference type?

Nullable reference type explicitly specifies whether a variable must contain a value or may not.

Key Features

  • Design-time analysis
  • Explicit API contracts
  • Search for potential locations with NullReference

πŸ“‘ Software requirements

  • .NET Standard 2.1+
  • Unity 2021+

πŸ“ƒ How to turn on static analysis

To analyze the individual assemblies

Create a csc.rsp file next to the asmdef:

Add the nullable argument to the contents of csc.rsp:

1
-nullable:enable

To analyze individual .cs files

Add the #nullable annotation context to the .cs content:

1
#nullable enable

πŸ’» Migration Guide

What to do with Unity UI bindings and DI Inject attributes?

Explicitly tell the analyzer that you guarantee their assignment and suppress the warnings using the ! null-forgiving operator.

Unity UI example:

1
[SerializeField] private Image _image = null!;

VContainer DI example:

1
2
3
4
5
6
7
8
9
10
namespace Sandbox.Domain
{
    private MoveController _moveController = null!;

    [Inject]
    public void Init(MoveController moveController)
    {
        _moveController = moveController;
    }
}

To exclude a separate part of the code from analysis, you can use the following annotation:

1
2
3
4
5
6
7
8
9
10
11
12
13
#nullable disable

using System;

namespace Sandbox.Server.Responses
{
    [Serializable]
    public class UserResponse
    {
        public int Id;
        public string Name;
    }
}

🎁 Helpful Links

Nullable reference types in Unity

Microsoft guide

This post is licensed under CC BY 4.0 by the author.