最近需要一个五角星的模型,自己琢磨着用代码实现出来,主要用到了unity中的Mesh类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class meshCreate : MonoBehaviour {
Mesh _mesh;
// Use this for initialization
void Start ()
{
//mesh类
_mesh = transform.GetComponent<MeshFilter>().mesh;
//mesh中的vertices顶点,组成网格的顶点,在顶点数组中有序存放
Vector3[] vec3 = {new Vector3(0,0,0),new Vector3(3,0,0),new Vector3(2,2,0),new Vector3(3,3,0),new Vector3(1.8f,3f,0),new Vector3(1.5f,4.5f,0),new Vector3(0.6f,3,0),new Vector3(0,3,0) };
_mesh.vertices = vec3;
//uv坐标范围:左下角(0,0),右上角(1,1),将2d的图片贴到3d的模型上
//mesh中的每个顶点的uv值,和每个顶点一一对应
Vector2[] vec2 = { new Vector2(2,0),new Vector2(1,0),new Vector2(1,1),new Vector2(0,1),new Vector2(0,1),new Vector2(1,1),new Vector2(0.2f,0.3f),new Vector2(0.5f,0.9f)};
_mesh.uv = vec2;
//mesh的triangles数组,数组的个数应为3的正整数倍,0对应顶点数组中的vec3[0],1对应顶点数组中的vec3[1],以此类推;每三个顶点构成一个三角形
//模型都是由某干个三角形组成,但是不同的顶点却可以有不同的组合三角形的方式,不同的组合三角形方式直接影响模型的形状,所以这里
//要对这种组合方式进行一定限制,这就是triangles数组的含义了。
int[] tri = {0,2,5,1,4,7,0,3,4};
// int[] tri = { 0,1,2,0,2,3};
_mesh.triangles = tri;
}
}
效果如下: