Combined mesh is positioned far away from gameObject?

I used this code (from Unity Scripting API reference) [ Mesh.CombineMeshes ] :

MeshFilter[ ] meshFilters = GetComponentsInChildren();
CombineInstance[ ] combine = new CombineInstance[meshFilters.Length];
int k = 0;
while (k < meshFilters.Length) {
combine[k].mesh = meshFilters[k].sharedMesh;
combine[k].transform = meshFilters[k].transform.localToWorldMatrix;
meshFilters[k].gameObject.active = false;
k++;
}
transform.GetComponent<MeshFilter>().mesh = new Mesh();
transform.GetComponent().mesh.CombineMeshes(combine);
transform.gameObject.active = true;

The mesh is combined OK however it’s positioned far away from the gameObject’s pivot. So after running the code, the gameObject seems to disappear but in fact its new combined mesh is rendered at some distance far away from its pivot.

I think there is something wrong with the combine[k].transform . At least this is not my code, it’s the code from the scripting reference. I guessed the code was tested against some simple model but failed to work with my models. Could you please suggest something to solve this? Thanks for your help.

I’ve solved the problem myself. As I doubted before, we have to do something with the combine[k].transform.
After converting each meshfilter’s transform from local to world space, we have to convert them back to local space of the parent gameObject. So I just need to change the combine[k].transform assignment to this:

combine[k].transform = transform.worldToLocalMatrix * meshFilters[k].transform.localToWorldMatrix;

9 Likes

This editor is so buggy and hopeless for code content. I simply wanted to type the square brackets with the index i inside but it interprets all those as italic format block. So I replaced the index i with k in my code above. This nasty bug should be fixed as soon as possible.

Wow, I’m actually having the same “issue”. I’ll try your way! Thank you! Nice timing.

Wow, this actually worked! Thank you VipHaLongPro! How is this not standard in the documentation?

Cleaned up the code:
combine[k].mesh = meshObjects[k].GetComponent ().sharedMesh;
combine[k].transform = meshObjects[k].transform.localToWorldMatrix * meshObject[k].transform.parent.transform.worldToLocalMatrix;

1 Like