• Unity
  • Flickering and a solution for it

So since updating to 4.2 and to the new runtimes I noticed sometimes that our characters flicker. Every other frame the mesh was getting 0 triangles. After wondering if it was our fault I realized that spine was double buffering mesh updates and this seemed like a perfect explanation for the every-other-frame nature of the bug.

Basically I tracked it down to Spine resizing the vertex array and thus clearing the meshes

Vector3[] vertices = this.vertices;
bool newTriangles = vertexCount > vertices.Length;
if (newTriangles) {
    // Not enough vertices, increase size.
    this.vertices = vertices = new Vector3[vertexCount];
    this.colors = new Color32[vertexCount];
    this.uvs = new Vector2[vertexCount];
    mesh1.Clear();
    mesh2.Clear();
}

The next update one of the meshes would receive the new triangles and new vertices but in the off chance the system didn't need to update the 2nd mesh the next frame it would skip it, leaving its triangle count at 0. Eventually some updates in the animations would happen at the right time and force spine to update the mesh structure, but depending on the exact animation our characters could flicker for several seconds first.

To fix this I added 2 new variables to the LastState: forceUpdateMesh1, forceUpdateMesh2. Set both to true when you clear the meshes. Then add this to CheckIfMustUpdateMeshStructure:

mustUpdateMeshStructure |= (useMesh1 ? lastState.forceUpdateMesh1 : lastState.forceUpdateMesh2);

When you actually update the mesh triangles set the appropriate variable. This will ensure that no matter what both cleared meshes receive the necessary updates the next time that mesh is used.

if (mustUpdateMeshStructure) {
    int submeshCount = submeshMaterials.Count;
    mesh.subMeshCount = submeshCount;
    for (int i = 0; i < submeshCount; ++i)
        mesh.SetTriangles(submeshes.Items[i].triangles, i);

if(useMesh1)
    lastState.forceUpdateMesh1 = false;
else
    lastState.forceUpdateMesh2 = false;
} 
Related Discussions
...
20 days later
a month later

Great find OP! Strange that this only started happening for me recently, could be due to increased complexity of my SkeletonAnimations.

@[deleted]
Do you have skeleton data you can share that causes the flickering? I'd like to try to apply this fix but I can't seem to reproduce the original problem.