The RequireComponent attribute automatically adds required components as dependencies.
When you add a script which uses RequireComponent to a GameObject, the required component is automatically 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. When you use RequireComponent, this is done automatically, so you are unlikely to get the setup wrong.
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
void Start()
{
var rb = GetComponent<Rigidbody>();
...
}
}Use RequiredComponent attribute:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
void Start()
{
var rb = GetComponent<Rigidbody>();
...
}
}A code fix is offered for this diagnostic to automatically apply this change.