Search Unity

Can I call SkinnedMeshRenderer.BakeMesh from an editor window?

Discussion in 'Animation' started by oboforty, Aug 25, 2022.

  1. oboforty

    oboforty

    Joined:
    Dec 3, 2019
    Posts:
    5
    Hello,

    Does SkinnedMeshRenderer.BakeMesh work within the editor? I'm trying to call BakeMesh after updating an animationClip, which seems to update my animation in the editor. I'd like to avoid using the Update loops, as I'm pre-rendering animation textures.

    But apparently I get the same vertices for my mesh (probably frame 0), should I refactor my editor window so that it waits some time for rendering before continuing to the next frame? Is there a better way to achieve this?

    Code (CSharp):
    1.  
    2. void OnGUI()
    3. {
    4.   // ...
    5.   if (GUILayout.Button("Render AnimTexture"))
    6.   {
    7.             // ...
    8.  
    9.             Mesh mesh = rend.sharedMesh;
    10.             var animClip = animations[0];
    11.             int nRowsAni = Mathf.CeilToInt(30 * animClip.length);
    12.             int nColsVtx = mesh.vertices.Length;
    13.  
    14.             for (int frame = 0; frame < nRowsAni; frame += 1)
    15.             {
    16.                 float bakeDelta = Mathf.Clamp01(((float)frame / nRowsAni));
    17.                 float animationTime = bakeDelta * animClip.length;
    18.                 animClip.SampleAnimation(obj, animationTime);
    19.                 rend.BakeMesh(mesh);
    20.                 // sample each transform in rig
    21.                 for (int vtxId = 0; vtxId < nColsVtx; vtxId++)
    22.                 {
    23.                     var vtx = mesh.vertices[vtxId];
    24.                     if (vtx.x < minVertices[vtxId].x) minVertices[vtxId].x = vtx.x;
    25.                     if (vtx.x > maxVertices[vtxId].x) maxVertices[vtxId].x = vtx.x;
    26.                     if (vtx.y < minVertices[vtxId].y) minVertices[vtxId].y = vtx.y;
    27.                     if (vtx.y > maxVertices[vtxId].y) maxVertices[vtxId].y = vtx.y;
    28.                     if (vtx.z < minVertices[vtxId].z) minVertices[vtxId].z = vtx.z;
    29.                     if (vtx.z > maxVertices[vtxId].z) maxVertices[vtxId].z = vtx.z;
    30.                 }
    31.             }
    32.  
    33.             //...
    34.   }
    35. }
    36.