Skip to content

Latest commit

 

History

History
40 lines (31 loc) · 917 Bytes

File metadata and controls

40 lines (31 loc) · 917 Bytes

UNT0026 GetComponent always allocates

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.