Version: 2017.3 (switch to 2017.4)
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

RequireComponent

class in UnityEngine

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

The RequireComponent attribute automatically adds required components as dependencies.

When you add a script which uses RequireComponent to a GameObject, the required component will automatically be added to the GameObject. This is useful to avoid setup errors. For example a script might require that a Rigidbody is always added to the same GameObject. Using RequireComponent this will be done automatically, thus you can never get the setup wrong. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added.

// PlayerScript requires the GameObject to have Rigidbody component
@script RequireComponent(Rigidbody)

var rb: Rigidbody;

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

function FixedUpdate() { rb.AddForce(Vector3.up); }
using UnityEngine;

// PlayerScript requires the GameObject to have a Rigidbody component [RequireComponent(typeof(Rigidbody))] public class PlayerScript : MonoBehaviour { Rigidbody rb;

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

void FixedUpdate() { rb.AddForce(Vector3.up); } }

Constructors

RequireComponentRequire a single component.

Did you find this page useful? Please give it a rating: