DEV Community

Cover image for Setup Nullable reference type in Unity
dreamcodestudio
dreamcodestudio

Posted on • Edited on

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:

csc.rsp path

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

-nullable:enable
Enter fullscreen mode Exit fullscreen mode

To analyze individual .cs files

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

#nullable enable
Enter fullscreen mode Exit fullscreen mode

nullable context

💻 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:

[SerializeField] private Image _image = null!;
Enter fullscreen mode Exit fullscreen mode

VContainer DI example:

namespace Sandbox.Domain
{
    private MoveController _moveController = null!;

    [Inject]
    public void Init(MoveController moveController)
    {
        _moveController = moveController;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

#nullable disable

using System;

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

🎁 Helpful Links

Nullable reference types in Unity

Microsoft guide

Top comments (0)