Unity学习(八)动态合并网格

标签:
unity优化 |
分类: Unity |
unity支持合并动态对象网格和静态对象网格,但是合并动态网格的条件实在太苛刻,像场景中固定不动的物件可以使用StaticBatchingUtility合并。具体的信息看官方文档或者http://blog.sina.com.cn/s/blog_471132920101gbfr.html
Unity的第三方插件功能倒是很强大,比如MeshBaker2,可以将MeshRender和SkinedMeshRender进行合并,但是做项目游戏对象都是动态生成,所以就找了找动态合并的方法。
原理大致如下:
1.获取网格烘焙器
2.获取材质烘焙器
3.创建烘焙结果集,并创建材质球,以及添加需要合并的对象,然后合并图集。
4.将结果集指定给网格烘焙器
5.合并网格
效果如下:
顶问题来了,unity一个mesh的顶点上限是64K,一个模型2k-3k顶点,那么能同时使用这种合并方式创建的对象个数也就30来个,而且当对象个数多的时候,创建新的就会有卡顿现象(可能是我没用好?),尽管如此,这么多的对象只消耗一个DC!http://www/uc/myshow/blog/misc/gif/E___6743EN00SIGG.gif
测试代码如下,仅供参考:
-
using
UnityEngine; -
using
System.Collections.Generic; -
-
-
public
class BakeTexturesAtRuntime : MonoBehaviour -
{
-
// 用于测试创建的对象 -
public GameObject resObj1; -
public GameObject resObj2; -
// 合并的主脚本对象 -
public GameObject target; -
-
// 用于合并的资源原始对象,带meshrender -
public GameObject obj1; -
public GameObject obj2; -
private List newobjs = List(); -
-
private MB2_MeshBaker meshbaker; -
private MB2_TextureBaker textureBaker; -
-
-
void Start() -
{ -
// 网格烘焙器 -
meshbaker = target.GetComponent(); -
// 材质烘焙器 -
textureBaker = target.GetComponent(); -
// 材质烘焙结果集 -
textureBaker.textureBakeResults = ScriptableObject.CreateInstance(); -
// 创建材质球 -
textureBaker.resultMaterial = new Material(Shader.Find( "Diffuse")); -
// 测试要合并的两个对象,将网格指定给材质 -
List resList = new List(); -
resList.Add(resObj1); -
resList.Add(resObj2); -
textureBaker.objsToMesh = resList; -
// 创建图集 -
textureBaker.CreateAtlases(); -
// 指定材质结果集到网格烘焙器 -
meshbaker.textureBakeResults = textureBaker.textureBakeResults; -
} -
-
private int i 0;= -
void OnGUI(){ -
-
if (GUILayout.Button( "创建新的对象")) -
{ -
GameObject go; -
if (i% 2== 0) -
{ -
go = (GameObject)Instantiate(obj1); -
} -
else -
{ -
go = (GameObject)Instantiate(obj2); -
} -
go.GetComponent().cullingType = AnimationCullingType.AlwaysAnimate; -
go.transform.localPosition = new Vector3(i++, 0,0); -
-
objs.Add(go.GetComponentInChildren().gameObject); -
-
// 添加到合并列表 -
meshbaker.AddDeleteGameObjects(objs.ToArray(), null); -
meshbaker.Apply(); -
} -
} - }