Unity 5.x: SubMesh + 多材质 的使用方式

来源:互联网 发布:bl漫画软件 编辑:程序博客网 时间:2024/06/05 02:41

本文讲述在Unity中,同一个Mesh中,使用多材质的方法。
比如:一张桌子可能会用到两种材质,桌腿用材质1,桌面用材质2。

Question : 同一个mesh,unity怎么知道桌腿用材质1,而桌面用材质2?

Answer : SubMesh

一个Mesh可以有多个SubMesh,
一个SubMesh对应着一个Material,
一个SubMesh可以有多个Triangle。

下面是unity 5.x脚本测试代码,有兴趣同学可以把玩一下。
参考Unity论坛

using UnityEngine;[RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))]public class TestSubMesh : MonoBehaviour{    void Start()    {        #region 设置Materials        // 程序事先设定的几个Material        Material[] materials = new Material[] {            Resources.Load("Materials/Red") as Material,            Resources.Load("Materials/Green") as Material,            Resources.Load("Materials/Gray") as Material,            Resources.Load("Materials/Blue") as Material,        };        this.GetComponent<MeshRenderer>().materials = materials;        #endregion        Mesh mesh = this.GetComponent<MeshFilter>().mesh;        mesh.Clear();        // 正四面体的顶点坐标        Vector3[] vertices = new Vector3[] {            new Vector3(0, 0, 0),            new Vector3(0, 1, 0),            new Vector3(Mathf.Sqrt(3)/2, 0.5f, 0),            new Vector3(Mathf.Sqrt(3) / 6, 0.5f, Mathf.Sqrt(6) / 3)        };        mesh.vertices = vertices;        mesh.subMeshCount = 4;        int[] triangle = new int[] { 0, 1, 2 };        mesh.SetTriangles(triangle, 0);        triangle = new int[] { 0, 3, 1 };        mesh.SetTriangles(triangle, 1);        Debug.Log(mesh.subMeshCount);        triangle = new int[] { 0, 2, 3 };        mesh.SetTriangles(triangle, 2);        triangle = new int[] { 1, 3, 2 };        mesh.SetTriangles(triangle, 3);        mesh.RecalculateNormals();    }}
原创粉丝点击