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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanghui_hn/article/details/77843519

本文讲述在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();
    }
}

猜你喜欢

转载自blog.csdn.net/zhanghui_hn/article/details/77843519
今日推荐