Skip to content

Latest commit

 

History

History
40 lines (30 loc) · 1.08 KB

File metadata and controls

40 lines (30 loc) · 1.08 KB

UNT0039 Use RequireComponent attribute when self-invoking GetComponent

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.