UNT0003 Usage of non generic GetComponent
January 12, 2022 ยท View on GitHub
Usage of the generic form of GetComponent, TryGetComponent, GetComponents, GetComponentInChildren, GetComponentsInChildren, GetComponentInParent, and GetComponentsInParent is preferred for type safety.
Examples of patterns that are flagged by this analyzer
using UnityEngine;
class Camera : MonoBehaviour
{
private Rigidbody rb;
private void Start()
{
rb = GetComponent(typeof(Rigidbody)) as Rigidbody;
}
}
Solution
Use the generic form of GetComponent:
using UnityEngine;
class Camera : MonoBehaviour
{
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
}
A code fix is offered for this diagnostic to automatically apply this change.