RequireComponent
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 33 of 67.
[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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch