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

本文讲述在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().materials = materials;
        #endregion


        Mesh mesh = this.GetComponent().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();
    }
}

你可能感兴趣的:(unity)