The RequireComponent attribute lets automatically add required component as a dependency.
When you add a script which uses RequireComponent, the required component will automatically be added to the game object. This is useful to avoid setup errors. For example a script might require that a rigid body is always added to the same game object. Using RequireComponent this will be done automatically, thus you can never get the setup wrong.
// The GameObject requires a RigidBody component @script RequireComponent(Rigidbody)
var rb: Rigidbody;
function Start() { rb = GetComponent.<Rigidbody>(); }
function FixedUpdate() { rb.AddForce(Vector3.up); }
using UnityEngine;
// The GameObject requires a Rigidbody component [RequireComponent (typeof (Rigidbody))] public class PlayerScript : MonoBehaviour { Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { rb.AddForce(Vector3.up); } }
RequireComponent | Require a single component. |