UNT0026 GetComponent always allocates
January 12, 2022 ยท View on GitHub
Component.TryGetComponent or GameObject.TryGetComponent will attempt to retrieve the component of the given type. The notable difference compared to GetComponent is that this method does not allocate when the requested component does not exist.
Examples of patterns that are flagged by this analyzer
using UnityEngine;
class Camera : MonoBehaviour
{
public void Update()
{
var rb = gameObject.GetComponent<Rigidbody>();
if (rb != null) {
Debug.Log(rb.name);
}
}
}
Solution
Use TryGetComponent instead:
using UnityEngine;
class Camera : MonoBehaviour
{
public void Update()
{
if (gameObject.TryGetComponent<Rigidbody>(out var rb)) {
Debug.Log(rb.name);
}
}
}
A code fix is offered for this diagnostic to automatically apply this change.