Unity 关于CombineMeshes的一点使用心得

时间:2022-07-26 16:45:49

类 Mesh

方法 public void CombineMeshes(CombineInstance[] combine)

例 mesh.CombineMeshes(combine)

1.参数combine 的数组长度不能大于int16, 如有大量Mesh需要合并, 需要分批次进行

2.mesh中原有的Mesh将会被combine 中Mesh所代替, 所以如果希望保留调用者Mesh中的mesh数据, 需要一并放进combine 数组中, 并在调用CombineMeshes方法之前为原mesh引用创建新的实例

下面的例子展示了创建4个cube: [g0, g1, g2, g3], 并将g1g2g3的模型合并到g0上, (注意: 本次合并操作对g1g2g3本身并无影响, 合并后的g0将会有4个cube模型)

void Awake () {
        GameObject g0 = GameObject.CreatePrimitive(PrimitiveType.Cube);

        GameObject g1 = GameObject.CreatePrimitive(PrimitiveType.Cube);
        g1.transform.position = new Vector3(10, 0, 0);
        GameObject g2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
        g2.transform.position = new Vector3(0, 10, 0);
        GameObject g3 = GameObject.CreatePrimitive(PrimitiveType.Cube);
        g3.transform.position = new Vector3(0, 0, 10);

        mergerCombine(g0, g1);
        mergerCombine(g0, g2);
        mergerCombine(g0, g3);
}

void mergerCombine(GameObject ori, GameObject tar)
{
        MeshFilter[] meshFilters1 = ori.GetComponents<MeshFilter>();
        MeshFilter[] meshFilters2 = tar.GetComponents<MeshFilter>();

        MeshFilter[] meshFilters = new MeshFilter[meshFilters1.Length + meshFilters2.Length];
        meshFilters1.CopyTo(meshFilters, 0);
        meshFilters2.CopyTo(meshFilters, meshFilters1.Length);
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        for (int i = 0; i < meshFilters.Length; i++)
        {
            combine[i].mesh = meshFilters[i].sharedMesh;
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
        }
        ori.transform.GetComponent<MeshFilter>().mesh = new Mesh();
        ori.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
}