Required

Overview

The [Required] attribute helps ensure that a field is not left as null in the Unity Inspector, helping prevent common runtime errors by prompting the user to assign a value. When applied, the Inspector will display a warning if the field is left empty, alerting the developer to assign a value.

This attribute is particularly useful for references to GameObjects, Components, and other objects that are essential for the script’s functionality, reducing the risk of errors due to missing assignments.

Syntax and Examples

Note: These examples use Unity’s [SerializeField] on private fields to promote encapsulation. This approach can help protect internal data from unintended access by other scripts and maintain clean, organized code. For more details, see Unity’s documentation on SerializeField.

Using [Required] is straightforward. Simply apply the attribute above the field you want to enforce as non-null.

Basic Syntax

[Required]
[SerializeField]
private GameObject importantObject;

Additional Constructor Syntax

// Custom error message
[Required("Custom error message")]

Example 1: Ensuring a GameObject Reference

In this example, importantObject is a GameObject that must be assigned for the script to function correctly.

[Required]
[SerializeField]
private GameObject importantObject;

Result: In the Inspector, a warning will appear if importantObject is left unassigned, prompting you to assign a value.

Gif of Example 1 result

Example 2: Enforcing a Required Component Reference

You can also use [Required] with specific component references, such as Rigidbody, to ensure they are assigned before runtime, and specify a custom error message to be displayed if not set.

[Required("Custom Error Message")]
[SerializeField]
private Rigidbody playerRigidbody;

Result: If playerRigidbody is left unassigned in the Inspector, a warning will alert you, saying “Custom Error Message”, until a Rigidbody reference has been assigned, preventing potential runtime errors.

Gif of Example 2 result