12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- using UnityEditor;
- using UnityEngine;
- using System.IO;
- using System.Text;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- public class CombineMeshes : Editor
- {
- private static GameObject targetMesh;
- private static string savedName = "_mesh";
- // 工具栏新增按钮
- [MenuItem("My Tools/Combine Selected Mesh", false, 100)]
- // 合并模型
- public static void CombineSelectedMesh()
- {
- //要处理的目标模型 所有要合并的模型需要放在该模型下
- targetMesh = Selection.activeGameObject;//GameObject.Find("Cube11");
- //获取自身和所有子物体中MeshRenderer组件
- MeshRenderer[] meshRenderers = targetMesh.GetComponentsInChildren<MeshRenderer>();
- //新建材质球数组
- Material[] materialList = new Material[meshRenderers.Length];
- for (int i = 0; i < meshRenderers.Length; i++)
- {
- //生成材质球数组
- materialList[i] = meshRenderers[i].sharedMaterial;
- }
- // 合并mesh
- //获取自身和所有子物体中所有MeshFilter组件
- MeshFilter[] meshFilters = targetMesh.GetComponentsInChildren<MeshFilter>();
- // 合并器
- 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;
- // 隐藏源模型模型
- meshFilters[i].gameObject.SetActive(false);
- }
- //新建一个物体 to saving combined mesh
- GameObject g = new GameObject();
- g.transform.name = targetMesh.transform.name + savedName;
- //物体和mesh来源物体同级
- g.transform.SetParent(targetMesh.transform.parent);
- //设置排序
- g.transform.SetSiblingIndex(targetMesh.transform.GetSiblingIndex() + 1);
- // 新建mesh
- g.AddComponent<MeshFilter>().mesh = new Mesh();
- //合并Mesh. 第二个参数:true合并为一个网格. false合并为子网格
- g.GetComponent<MeshFilter>().sharedMesh.CombineMeshes(combine, false);
- // set avaliable be true
- g.gameObject.SetActive(true);
- //为合并后的新Mesh指定材质
- g.AddComponent<MeshRenderer>().sharedMaterials = materialList;
- }
- //点击该按钮 保存网格资源到Asset目录
- [MenuItem("My Tools/Save Selected Mesh To Asset", false, 101)]
- public static void SaveSelectedMeshToAsset()
- {
- Mesh mesh = Selection.activeGameObject.GetComponent<MeshFilter>().sharedMesh;
- AssetDatabase.CreateAsset(mesh, "Assets/" + targetMesh.transform.name + savedName + ".asset");
- AssetDatabase.SaveAssets();
- }
- }
|