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.
using UnityEngine;
class Camera : MonoBehaviour
{
public void Update()
{
var rb = gameObject.GetComponent<Rigidbody>();
if (rb != null) {
Debug.Log(rb.name);
}
}
}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.