UNT0022 Inefficient method to set position and rotation

October 17, 2023 ยท View on GitHub

Accessing the Transform/TransformAccess should be done as few times as possible for performance reasons. Instead of setting position and rotation sequentially, you should use SetPositionAndRotation() method.

Examples of patterns that are flagged by this analyzer

using UnityEngine;

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

Solution

Fix assignment:

using UnityEngine;

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

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