Unity教程之-合併(Combine)引用相同材質球的網格(Mesh)
阿新 • • 發佈:2019-01-22
functionCombineMeshes(combine: CombineInstance[],mergeSubMeshes: bool = true,useMatrices: bool = true) : void
結合網格有利於效能最優化。如果mergeSubMeshes為true,所有的網格會被結合成一個單個子網格。否則每一個網格都將變成單個不同的子網格。如果所有的網格共享同一種材質,設定它為真。如果useMatrices為false,在CombineInstance結構中的變換矩陣將被忽略。
用這函式我們可以把引用相同材質球的網格進行合併達到減少Draw Call,優化效能的效果。
我的基本思路是:將所有的材質球用字典存(相同的只存一個),將引用相同材質球的網格存一個連結串列中用材質球的名稱作為Key值;
然後遍歷字典用Mesh的成員方法CombineMeshes()合併相同;
OK,上程式碼
好了,本篇unity3d教程關於合併相同材質的mesh網格的教程到此結束,下篇我們再會!using UnityEngine; using System.Collections; using System.Collections.Generic; public class ComebinMesheDemo : MonoBehaviour { // Use this for initialization void Start () { //獲取所有網格過濾器; MeshFilter[] meshFilters = gameObject.GetComponentsInChildren<MeshFilter>(); //存放不同的材質球,相同的就存一個; Dictionary<string, Material> materials = new Dictionary<string, Material>(); //存放要合併的網格物件; Dictionary<string, List<CombineInstance>> combines = new Dictionary<string, List<CombineInstance>>(); for (int i = 0; i < meshFilters.Length; i++) { //構造一個網格合併結構體; CombineInstance combine = new CombineInstance(); //給結構體的mesh賦值; combine.mesh = meshFilters[i].mesh; combine.transform = meshFilters[i].transform.localToWorldMatrix; MeshRenderer renderer = meshFilters[i].GetComponent<MeshRenderer>(); Material mat = renderer.sharedMaterial; if (!materials.ContainsKey(mat.name)) { materials.Add(mat.name, mat); } if (combines.ContainsKey(mat.name)) { combines[mat.name].Add(combine); } else { List<CombineInstance> coms = new List<CombineInstance>(); coms.Add(combine); combines[mat.name] = coms; } Destroy(meshFilters[i].gameObject); } GameObject combineObj = new GameObject("Combine"); combineObj.transform.parent = transform; foreach (KeyValuePair<string, Material> mater in materials) { GameObject obj = new GameObject(mater.Key); obj.transform.parent = combineObj.transform; MeshFilter combineMeshFilter = obj.AddComponent<MeshFilter>(); combineMeshFilter.mesh = new Mesh(); //將引用相同材質球的網格合併; combineMeshFilter.mesh.CombineMeshes(combines[mater.Key].ToArray(), true,true); MeshRenderer rend = obj.AddComponent<MeshRenderer>(); //指定材質球; rend.sharedMaterial = mater.Value; rend.castShadows = false; rend.receiveShadows = true; } } }