1. 程式人生 > >Unity3D-Mesh建立

Unity3D-Mesh建立

Mesh需要用程式碼建立。

using UnityEngine;
using System.Collections;
using UnityEditor;

public class CreateMesh : MonoBehaviour 
{

    // 頂點集合
    private Vector3[] vertices = new Vector3[ConstNumber.PointSum];

    // 三角形索引 一共(ConstNumber.XLength - 1) * (ConstNumber.YLength - 1)個矩形 ,每個矩形6個點
    private int[] triangles = new int[6 * (ConstNumber.XLength - 1) * (ConstNumber.YLength - 1)];

    private Color[] colors = new Color[ConstNumber.PointSum];

	// Use this for initialization
	void Start () 
    {
        CreateMeshFun();
	}

    public void CreateMeshFun()
    {
        Mesh mesh = new Mesh();
        mesh = CreateMeshObject();
        AssetDatabase.CreateAsset(mesh, "Assets/" + "Pollutant" + ".asset");

        //列印新建資源的路徑
        // Debug.Log(AssetDatabase.GetAssetPath(mesh));

    }

    private Mesh CreateMeshObject()
    {
        Mesh mesh = new Mesh();

        // 初始化頂點位置
        initVertexPos();

        //三角形索引
        initTriangles();

        //初始化顏色
        initColors();
        
        // 頂點賦值
        mesh.vertices = vertices;
        // 索引賦值
        mesh.triangles = triangles;

        // 對頂點著色
        mesh.colors = colors;
        // 重新計算網格的法線
        mesh.RecalculateNormals();
        return mesh;
    }

    // 初始化頂點位置
    private void initVertexPos()
    {
        int currentIndex = 0;

        for (int i = 0; i < ConstNumber.YLength; i++)
        {
            for (int j = 0; j < ConstNumber.XLength; j++)
            {
                vertices[currentIndex] = new Vector3(j, 0, i);
                currentIndex++;
            }
        }
    }

    // 初始化三角形索引
    private void initTriangles()
    {
        // 代表triangl陣列當前索引值,每放入陣列中一個值,currentIndex都增1
        int currentIndex = 0;
        
        for (int i = 0; i < ConstNumber.YLength - 1; i++)
        {
            for (int j = 0; j < ConstNumber.XLength - 1; j++)
            {
                // 順時針畫左上角三角形
                triangles[currentIndex++] = (i + 0) * ConstNumber.XLength + (j + 0);
                triangles[currentIndex++] = (i + 1) * ConstNumber.XLength + (j + 0);
                triangles[currentIndex++] = (i + 1) * ConstNumber.XLength + (j + 1);

                // 順時針畫右下角三角形
                triangles[currentIndex++] = (i + 0) * ConstNumber.XLength + (j + 0);
                triangles[currentIndex++] = (i + 1) * ConstNumber.XLength + (j + 1);
                triangles[currentIndex++] = (i + 0) * ConstNumber.XLength + (j + 1);

            }
        }
         
    }

    // 初始化顏色
    private void initColors()
    {
        for (int i = 0; i < ConstNumber.PointSum; i++)
        {
            Color color = new Color(0, 0, 0);
            colors[i] = color;
        }
    }
}

會生成長為XLength 寬為YLength的矩形Mesh


oK,拖入,Hierarchy面板,得到GameObject


Mesh建立完畢了