有时候我们会建立简单的小模型,比如先创建一个空物体,然后在空物体下面摆放几个小物体,位置摆放好之后我们只需要拖动空的父节点就行啦,然后我们就可以无耻的把它看成“一个”新的模型。如图(有点丑)
555.png
为了表示这是三个不同的物体,我先分别用了不同的材质球赋值给他们,方便大家看清楚。
但是在实际项目中,只有子物体所用同一材质我们才考虑合并,不然合并后用什么材质呢?肯定达不到以前的样子了。
777.png
开始正题啦
下面便是我们的编辑器脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MeshCombine : EditorWindow {
static GameObject MeshTarget;
static Material material;
bool isCombine = false;
[MenuItem("MyWindow/MeshCombineWindow")]
private static void AddWindow2()
{
Rect _rect = new Rect(0, 0, 500, 500);
MeshCombine window = (MeshCombine)EditorWindow.GetWindowWithRect(typeof(MeshCombine), _rect, true, "MeshCombine");
window.Show();
}
private void OnGUI()
{
MeshTarget = EditorGUILayout.ObjectField("添加最终物体", MeshTarget,typeof(GameObject),true)as GameObject;
material = EditorGUILayout.ObjectField("添加最终显示材质", material, typeof(Material), true) as Material;
EditorGUILayout.BeginVertical();
Color c = GUI.color;
if (isCombine) GUI.color = Color.green;
else GUI.color = Color.white;
if (GUILayout.Button("合并mesh网格", GUILayout.Width(200)))
{
MeshTarget.AddComponent<MeshFilter>();
MeshTarget.AddComponent<MeshRenderer>();
CombineMesh();
isCombine = true;
}
GUI.color = c;
EditorGUILayout.Space();
if (GUILayout.Button("关闭窗口", GUILayout.Width(200)))
{
//关闭窗口
this.Close();
}
EditorGUILayout.EndVertical();
}
static void CombineMesh()
{
MeshFilter[] meshFilters = MeshTarget.GetComponentsInChildren<MeshFilter>();
CombineInstance[] combineInstances = new CombineInstance[meshFilters.Length];
for (int i = 0; i < meshFilters.Length; i++)
{
combineInstances[i].mesh = meshFilters[i].sharedMesh;
combineInstances[i].transform = meshFilters[i].transform.localToWorldMatrix;
}
Mesh targetMesh = new Mesh();
targetMesh.CombineMeshes(combineInstances);
MeshTarget.GetComponent<MeshFilter>().sharedMesh = targetMesh;
MeshTarget.GetComponent<Renderer>().material = material;
}
}
下面便是我们自己扩展的编辑器窗口啦,只需要把这个空的父节点拖到第一个物体输入框。然后在第二个材质框为我们的新物体赋值一个材质,最后动动你的小手,点击一下合并材质的按钮就行啦
666.png
注意
在项目后期我们经常会对项目进行优化,而合并材质也可以减少物体个数,减少drawcall次数。但是进行合并的前提要求是这些分个的小子物体使用的是同一材质球,这样合并后就能达到和以前同样的效果啦
888.png
注意,这里原来父节点下面的所有子物体都被我隐藏啦,但是显示是和原来一模一样的。
好了,本次水文结束。