Monthly Archives: August 2016

Save Time and Hassle with RequireComponent

You can use [code]]czoxNjpcIlJlcXVpcmVDb21wb25lbnRcIjt7WyYqJl19[[/code] 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 [code]]czoxMDpcIkdhbWVPYmplY3RcIjt7WyYqJl19[[/code] 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 [code]]czoxMDpcIkdhbWVPYmplY3RcIjt7WyYqJl19[[/code] while the script is attached, which could prevent accidents like removing the wrong component.

Here is a simple example:

public class PlayerInput : MonoBehaviour
    Collider playerCol;
    void Start()
        playerCol = GetComponent<Collider>();

The above [code]]czoxMTpcIlBsYXllcklucHV0XCI7e1smKiZdfQ==[[/code] script requires that a collider is attached to any [code]]czoxMDpcIkdhbWVPYmplY3RcIjt7WyYqJl19[[/code] this script is added to. Now you can be confident that the assignment of the collider to [code]]czo5OlwicGxheWVyQ29sXCI7e1smKiZdfQ==[[/code] will always find a collider ([code]]czoxMjpcIkdldENvbXBvbmVudFwiO3tbJiomXX0=[[/code] is a common source of null reference errors, which this technique avoids completely).

Consider using [code]]czoxNjpcIlJlcXVpcmVDb21wb25lbnRcIjt7WyYqJl19[[/code] to save yourself a bit of time and many headaches.