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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground