合并网格(Mesh)

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

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

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

05.png

 

代码

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class CombineMeshTest : MonoBehaviour {
  6.  
  7. public MeshFilter cubeFilter;
  8. public MeshRenderer cubeRenderer;
  9. public MeshFilter sphereFilter;
  10. public MeshRenderer sphereRenderer;
  11.  
  12. private MeshFilter selfFilter;
  13. private MeshRenderer selfRenderer;
  14. void Start () {
  15. selfRenderer = GetComponent<MeshRenderer>();
  16. selfFilter = GetComponent<MeshFilter>();
  17. selfFilter.mesh = new Mesh();
  18.  
  19. List<CombineInstance> cilist = new List<CombineInstance>();
  20.  
  21. CombineInstance ci1 = new CombineInstance();
  22. ci1.mesh = cubeFilter.sharedMesh;
  23. ci1.transform = cubeFilter.transform.localToWorldMatrix;
  24.  
  25. CombineInstance ci2 = new CombineInstance();
  26. ci2.mesh = sphereFilter.sharedMesh;
  27. ci2.transform = sphereFilter.transform.localToWorldMatrix;
  28.  
  29. cilist.Add(ci1);
  30. cilist.Add(ci2);
  31.  
  32. Material[] mats = new Material[2];
  33. mats[0] = cubeRenderer.sharedMaterial;
  34. mats[1] = sphereRenderer.sharedMaterial;
  35.  
  36. selfRenderer.sharedMaterials = mats;
  37. /*
  38. * 合并网格对于优化性能很有用。如果mergeSubMeshes为true,所有的网格合并到单个的子网格,
  39. * 否则每网格将合并到不同的子网格,如果所有网格共享同一材质,设置这个为true。
  40. * 如果useMatrices为false,在CombineInstance结构变换矩阵将被忽略。
  41. */
  42. selfFilter.mesh.CombineMeshes(cilist.ToArray(), false, true);
  43. }
  44. }

 

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号