API
使用Unity官方API,Mesh.CombineMeshes
https://docs.unity3d.com/cn/2021.2/ScriptReference/Mesh.CombineMeshes.html
示例代码:
using UnityEngine; using System.Collections; // Copy meshes from children into the parent's Mesh. // CombineInstance stores the list of meshes. These are combined // and assigned to the attached Mesh. [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class ExampleClass : MonoBehaviour { void Start() { MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; int i = 0; while (i < meshFilters.Length) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix; meshFilters[i].gameObject.SetActive(false); i++; } transform.GetComponent<MeshFilter>().mesh = new Mesh(); transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine); transform.gameObject.SetActive(true); } }
执行结果
图1,合并前
图2,合并后
如图,可以看到合并后网格并不在期望的位置。
主要原因是transform.localToWorldMatrix。
如果我们此时将localToWorldMatrix换成worldToLocalMatrix ,对图2的物体再进行网格合并,会得到图1的结果。
解决方案
由此我们可以知道,现在的Unity中的mesh.transform如使用transform.localToWorldMatrix,会导致合并后的网格偏移。
并且偏移的量,就是其transform.worldToLocalMatrix。
其实我们根本不需要让transform由本地空间转换到世界空间的矩阵。但是并没有transform直接转换成矩阵的方法。
所以我们再转换后,再给他转换回去就可以了。
在localToWorldMatrix 后乘 meshFilters[i].transform.worldToLocalMatrix (使用其父物体的worldToLocalMatrix 也可)
combine[i].transform = meshFilters[i].transform.localToWorldMatrix * meshFilters[i].transform.worldToLocalMatrix ;
完整代码
using UnityEngine; using System.Collections; // Copy meshes from children into the parent's Mesh. // CombineInstance stores the list of meshes. These are combined // and assigned to the attached Mesh. [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class ExampleClass : MonoBehaviour { void Start() { MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; int i = 0; while (i < meshFilters.Length) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix * meshFilters[i].transform.worldToLocalMatrix ; meshFilters[i].gameObject.SetActive(false); i++; } transform.GetComponent<MeshFilter>().mesh = new Mesh(); transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine); transform.gameObject.SetActive(true); } }