合并网格(Mesh)

作者:追风剑情 发布于:2016-11-24 12:07 分类:Unity3d

一、创建1个Cube和Sphere
01.png
二、创建1个空GameObject取命为Combine,并挂上相应组件。
02.png

03.png
三、运行效果
04.png

05.png

 

代码

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CombineMeshTest : MonoBehaviour {

    public MeshFilter cubeFilter;
    public MeshRenderer cubeRenderer;
    public MeshFilter sphereFilter;
    public MeshRenderer sphereRenderer;

    private MeshFilter selfFilter;
    private MeshRenderer selfRenderer;
	void Start () {
        selfRenderer = GetComponent<MeshRenderer>();
        selfFilter = GetComponent<MeshFilter>();
        selfFilter.mesh = new Mesh();

        List<CombineInstance> cilist = new List<CombineInstance>();

        CombineInstance ci1 = new CombineInstance();
        ci1.mesh = cubeFilter.sharedMesh;
        ci1.transform = cubeFilter.transform.localToWorldMatrix;

        CombineInstance ci2 = new CombineInstance();
        ci2.mesh = sphereFilter.sharedMesh;
        ci2.transform = sphereFilter.transform.localToWorldMatrix;

        cilist.Add(ci1);
        cilist.Add(ci2);

        Material[] mats = new Material[2];
        mats[0] = cubeRenderer.sharedMaterial;
        mats[1] = sphereRenderer.sharedMaterial;

        selfRenderer.sharedMaterials = mats;
        /*
         * 合并网格对于优化性能很有用。如果mergeSubMeshes为true,所有的网格合并到单个的子网格,
         * 否则每网格将合并到不同的子网格,如果所有网格共享同一材质,设置这个为true。
         * 如果useMatrices为false,在CombineInstance结构变换矩阵将被忽略。
         */
        selfFilter.mesh.CombineMeshes(cilist.ToArray(), false, true);
	}
}

 

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号