UNT0039 Use RequireComponent attribute when self-invoking GetComponent
July 17, 2026 ยท View on GitHub
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.
Examples of patterns that are flagged by this analyzer
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
void Start()
{
var rb = GetComponent<Rigidbody>();
...
}
}
Solution
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.
Examples of patterns that are not flagged by this analyzer
GetComponent calls inside editor-only messages (Reset, OnValidate) are not flagged: those messages are typically used to populate serialized fields with default references that a user can override, so the component is not a hard requirement.
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public Rigidbody rb;
void Reset()
{
rb = GetComponent<Rigidbody>();
}
}