多语言展示
当前在线:921今日阅读:27今日分享:41

Unity Mesh教程 之 使用Mesh画一个三角形

Unity Mesh教程 之 使用Mesh画一个三角形。本节介绍如何使用Mesh画一个三角形出来的简单案例,具体如下
工具/原料
1

Unity

2

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:ComponentA class to access the Mesh of the mesh filter.Use this with a procedural mesh interface. See Also: Mesh class.

3

MeshRenderer:Inherits from:RendererRenders meshes inserted by the MeshFilter or TextMesh.

4

方法提示:1)要求必须添加“MeshFilter”和“MeshRender”组件2)把三角形值赋给“MeshFilter.mesh”

二、Mesh教程 之 使用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 points = new List ();    // 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 ().mesh = triangleMesh;    }}

5

脚本编译正确,回到Unity界面,在场景中新建一个“GameObject”,把脚本“MeshTriangleTest”赋给“GameObject”,你会看到自动加上组件“MeshFilter”和“MeshRender”,具体如下图

6

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

7

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

注意事项

您的支持,是我们不断坚持知识分享的动力,若帮到您,还请帮忙投票有得;若有疑问,请留言

推荐信息