Monthly Archives: August 2016

Save Time and Hassle with RequireComponent

You can use RequireComponent in your Unity scripts to save yourself some work and avoid errors.

When your script requires a component, Unity will add a component of that type to your GameObject automatically when you add your script (if a component of the required type is not already there). You also cannot remove this component form the GameObject while the script is attached, which could prevent accidents like removing the wrong component.

Here is a simple example:

[RequireComponent(typeof(Collider))]
public class PlayerInput : MonoBehaviour
{
    Collider playerCol;
    
    void Start()
    {
        playerCol = GetComponent<Collider>();
    }
}

The above PlayerInput script requires that a collider is attached to any GameObject this script is added to. Now you can be confident that the assignment of the collider to playerCol will always find a collider (GetComponent is a common source of null reference errors, which this technique avoids completely).

Consider using RequireComponent to save yourself a bit of time and many headaches.