UNT0032 Inefficient method to set localPosition and localRotation

October 17, 2023 ยท View on GitHub

Accessing the Transform/TransformAccess should be done as few times as possible for performance reasons. Starting with Unity 2021.3.11f1, instead of setting localPosition and localRotation sequentially, you should use SetLocalPositionAndRotation() method.

Examples of patterns that are flagged by this analyzer

using UnityEngine;

class Camera : MonoBehaviour
{
    void Update()
    {
        transform.localPosition = new Vector3(0.0f, 1.0f, 0.0f);
        transform.localRotation = transform.localRotation;
    }
}

Solution

Fix assignment:

using UnityEngine;

class Camera : MonoBehaviour
{
    void Update()
    {
        transform.SetLocalPositionAndRotation(new Vector3(0.0f, 1.0f, 0.0f), transform.localRotation);
    }
}

A code fix is offered for this diagnostic to automatically apply this change.