Menu
CoddyTech

RequireComponent

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 47 of 85.

[RequireComponent(typeof(Rigidbody))], written above a script's class, tells Unity that the script cannot work without a Rigidbody on the same object:

[RequireComponent(typeof(Rigidbody))]
public class Jumper : MonoBehaviour
{
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
}

Unity acts on it when the script is added to an object, in the Inspector or with AddComponent: if the object has no Rigidbody, Unity adds one. While Jumper is on the object, the Inspector refuses to remove that Rigidbody. So GetComponent here always finds one, and Jumper needs no check.

The attribute does not reach back: objects that already had Jumper before the line was written get no Rigidbody until the script is removed and added again. One attribute can name up to three types, as in [RequireComponent(typeof(Rigidbody), typeof(BoxCollider))], and a class can carry several of them.

Try it yourself

This lesson doesn't include a code challenge.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground