Unity Mesh教程 之 使用Mesh画一个三角形
1、Mesh:
A class that allows creating or modifying meshes from scripts.
Meshes contain vertices and multiple triangle arrays. See the Procedural example project for examples of using the mesh interface.The triangle arrays are simply indices into the vertex arrays; three indices for each triangle.For every vertex there can be a normal, two texture coordinates, color and tangent. These are optional though and can be removed at will. All vertex information is stored in separate arrays of the same size, so if your mesh has 10 vertices, you would also have 10-size arrays for normals and other attributes.
2、MeshFilter:
class in UnityEngine Inherits from:Component
A class to access the Mesh of the mesh filter.
Use this with a procedural mesh interface. See Also: Mesh class.
3、MeshRenderer:
Inherits from:Renderer
Renders meshes inserted by the MeshFilter or TextMesh.
4、方法提示:
1)要求必须添加“MeshFilter”和“MeshRender”组件
2)把三角形值赋给“MeshFilter.mesh”
1、打开Unity,新建一个空工程,具体如下

2、在工程中新建一个脚本“MeshTriangleTest”,双击脚本或者右键“Open C# Project”打开,具体如下图


3、在打开的脚本“MeshTriangleTest”上编写代码,首先添加要求“MeshFilter”和“MeshRender”组件,然后新建一个列表设置三角形顶点坐标,接着实现画三角形的函数,具体代码及代码说明如下图

4、“MeshTriangleTest”脚本的具体代码如下:
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class MeshTriangleTest : MonoBehaviour {
private List<Vector3> points = new List<Vector3> ();
// Use this for initialization
void Start () {
points.Add (new Vector3(0, 0, 0));
points.Add (new Vector3(0, 1, 0));
points.Add (new Vector3(1, 0, 0));
MeshDrawTriangle ();
}
private void MeshDrawTriangle() {
//新建一个Mesh
Mesh triangleMesh = new Mesh ();
//把列表的顶点坐标赋给Mesh的vertexs
triangleMesh.vertices = points.ToArray ();
//设置三角形顶点数量
int[] trianglePoints = new int[3];
trianglePoints [0] = 0;
trianglePoints [1] = 1;
trianglePoints [2] = 2;
//把三角形的数量给Mesh的三角形
triangleMesh.triangles = trianglePoints;
//设置三角形的相关参数
triangleMesh.RecalculateBounds ();
triangleMesh.RecalculateNormals ();
triangleMesh.RecalculateTangents ();
//把三角形的Mesh赋给MeshFilter组件
GetComponent <MeshFilter>().mesh = triangleMesh;
}
}
5、脚本编译正确,回到Unity界面,在场景中新建一个“GameObject”,把脚本“MeshTriangleTest”赋给“GameObject”,你会看到自动加上组件“MeshFilter”和“MeshRender”,具体如下图

6、运行场景,即可在游戏场景中看到画出的三角形,具体如下图

7、到此,《Unity Mesh教程 之 使用Mesh画一个三角形》讲解结束,谢谢