Skip to content

Latest commit

 

History

History
63 lines (50 loc) · 1.7 KB

File metadata and controls

63 lines (50 loc) · 1.7 KB

UNT0042 Mesh array property accessed in loop

Accessing array properties like vertices, normals, tangents, uv, colors, etc. on Mesh inside a loop causes a new array allocation on each access. This can significantly impact performance, especially in frequently called methods like Update().

Examples of patterns that are flagged by this analyzer

using UnityEngine;

class Example : MonoBehaviour
{
    void Update()
    {
        Mesh mesh = GetComponent<MeshFilter>().mesh;

        // Bad: mesh.vertices allocates a new array on every iteration
        for (int i = 0; i < mesh.vertices.Length; i++)
        {
            // ...
        }

        // Bad: mesh.vertices and mesh.normals allocate new arrays on every iteration
        for (int i = 0; i < mesh.vertexCount; i++)
        {
            mesh.vertices[i] += mesh.normals[i] * Time.deltaTime;
        }
    }
}

Solution

Cache the array property in a local variable before the loop:

using UnityEngine;

class Example : MonoBehaviour
{
    void Update()
    {
        Mesh mesh = GetComponent<MeshFilter>().mesh;

        // Good: cache the array before the loop
        Vector3[] vertices = mesh.vertices;
        for (int i = 0; i < vertices.Length; i++)
        {
            // ...
        }

        // Good: cache arrays before the loop, assign back after modifications
        Vector3[] verts = mesh.vertices;
        Vector3[] normals = mesh.normals;
        for (int i = 0; i < verts.Length; i++)
        {
            verts[i] += normals[i] * Time.deltaTime;
        }
        mesh.vertices = verts;
    }
}

A code fix is offered for this diagnostic to automatically cache the array property in a local variable.