UNITY材质球合并

您所在的位置:网站首页 c4d合并重复的材质球 UNITY材质球合并

UNITY材质球合并

2024-07-09 10:35| 来源: 网络整理| 查看: 265

材质球合并,分以下几步走,首先我们讨论普通的MeshRenderer的材质球合并,然后再讨论SkinnedMeshRenderer的材质球合并。

普通的MeshRenderer的材质球合并:

1.合并所有材质球所携带的贴图,新建一个材质球,并把合并好的贴图赋予新的材质球。

2.记录下每个被合并的贴图所处于新贴图的Rect,用一个Rect[]数组存下来。

3.合并网格,并把需要合并的各个网格的uv,根据第2步得到的Rect[]刷一遍。

4.把新的材质球赋予合并好的网格,此时就只占有1个drawcall了。

下面是关键代码:

void CombineMesh() { MeshFilter[] mfChildren = GetComponentsInChildren(); CombineInstance[] combine = new CombineInstance[mfChildren.Length]; MeshRenderer[] mrChildren = GetComponentsInChildren(); Material[] materials = new Material[mrChildren.Length]; MeshRenderer mrSelf = gameObject.AddComponent(); MeshFilter mfSelf = gameObject.AddComponent(); Texture2D[] textures = new Texture2D[mrChildren.Length]; for (int i = 0; i < mrChildren.Length; i++) { if (mrChildren[i].transform == transform) { continue; } materials[i] = mrChildren[i].sharedMaterial; Texture2D tx = materials[i].GetTexture("_MainTex") as Texture2D; Texture2D tx2D = new Texture2D(tx.width, tx.height, TextureFormat.ARGB32, false); tx2D.SetPixels(tx.GetPixels(0, 0, tx.width, tx.height)); tx2D.Apply(); textures[i] = tx2D; } Material materialNew = new Material(materials[0].shader); materialNew.CopyPropertiesFromMaterial(materials[0]); mrSelf.sharedMaterial = materialNew; Texture2D texture = new Texture2D(1024, 1024); materialNew.SetTexture("_MainTex", texture); Rect[] rects = texture.PackTextures(textures, 10, 1024); for (int i = 0; i < mfChildren.Length; i++) { if (mfChildren[i].transform == transform) { continue; } Rect rect = rects[i]; Mesh meshCombine = mfChildren[i].mesh; Vector2[] uvs = new Vector2[meshCombine.uv.Length]; //把网格的uv根据贴图的rect刷一遍 for (int j = 0; j < uvs.Length; j++) { uvs[j].x = rect.x + meshCombine.uv[j].x * rect.width; uvs[j].y = rect.y + meshCombine.uv[j].y * rect.height; } meshCombine.uv = uvs; combine[i].mesh = meshCombine; combine[i].transform = mfChildren[i].transform.localToWorldMatrix; mfChildren[i].gameObject.SetActive(false); } Mesh newMesh = new Mesh(); newMesh.CombineMeshes(combine, true,true);//合并网格 mfSelf.mesh = newMesh; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3