menu.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System.IO;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. public class CombineMeshes : Editor
  9. {
  10. private static GameObject targetMesh;
  11. private static string savedName = "_mesh";
  12. // 工具栏新增按钮
  13. [MenuItem("My Tools/Combine Selected Mesh", false, 100)]
  14. // 合并模型
  15. public static void CombineSelectedMesh()
  16. {
  17. //要处理的目标模型 所有要合并的模型需要放在该模型下
  18. targetMesh = Selection.activeGameObject;//GameObject.Find("Cube11");
  19. //获取自身和所有子物体中MeshRenderer组件
  20. MeshRenderer[] meshRenderers = targetMesh.GetComponentsInChildren<MeshRenderer>();
  21. //新建材质球数组
  22. Material[] materialList = new Material[meshRenderers.Length];
  23. for (int i = 0; i < meshRenderers.Length; i++)
  24. {
  25. //生成材质球数组
  26. materialList[i] = meshRenderers[i].sharedMaterial;
  27. }
  28. // 合并mesh
  29. //获取自身和所有子物体中所有MeshFilter组件
  30. MeshFilter[] meshFilters = targetMesh.GetComponentsInChildren<MeshFilter>();
  31. // 合并器
  32. CombineInstance[] combine = new CombineInstance[meshFilters.Length];
  33. //
  34. for (int i = 0; i < meshFilters.Length; i++)
  35. {
  36. // 合并模型
  37. combine[i].mesh = meshFilters[i].sharedMesh;
  38. //还原坐标状态
  39. combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
  40. // 隐藏源模型模型
  41. meshFilters[i].gameObject.SetActive(false);
  42. }
  43. //新建一个物体 to saving combined mesh
  44. GameObject g = new GameObject();
  45. g.transform.name = targetMesh.transform.name + savedName;
  46. //物体和mesh来源物体同级
  47. g.transform.SetParent(targetMesh.transform.parent);
  48. //设置排序
  49. g.transform.SetSiblingIndex(targetMesh.transform.GetSiblingIndex() + 1);
  50. // 新建mesh
  51. g.AddComponent<MeshFilter>().mesh = new Mesh();
  52. //合并Mesh. 第二个参数:true合并为一个网格. false合并为子网格
  53. g.GetComponent<MeshFilter>().sharedMesh.CombineMeshes(combine, false);
  54. // set avaliable be true
  55. g.gameObject.SetActive(true);
  56. //为合并后的新Mesh指定材质
  57. g.AddComponent<MeshRenderer>().sharedMaterials = materialList;
  58. }
  59. //点击该按钮 保存网格资源到Asset目录
  60. [MenuItem("My Tools/Save Selected Mesh To Asset", false, 101)]
  61. public static void SaveSelectedMeshToAsset()
  62. {
  63. Mesh mesh = Selection.activeGameObject.GetComponent<MeshFilter>().sharedMesh;
  64. AssetDatabase.CreateAsset(mesh, "Assets/" + targetMesh.transform.name + savedName + ".asset");
  65. AssetDatabase.SaveAssets();
  66. }
  67. }