创建网格
Mesh CurMesh = new Mesh();
CurMesh.name = "CreateMesh";
创建顶点
Vector3[] vectices = new Vector3[4] {
new Vector2(0,0),
new Vector2(0,1),
new Vector2(1,1),
new Vector2(1,0)
};
CurMesh.vertices = vectices;
连接顶点
int[] TriangleIndexs = new int[6] { 0, 1, 3, 3, 1, 2 };//简写方式
/* TriangleIndexs[0] = 0;
TriangleIndexs[1] = 1;
TriangleIndexs[2] = 3;
TriangleIndexs[3] = 3;
TriangleIndexs[4] = 1;
TriangleIndexs[5] = 2;*/
CurMesh.triangles = TriangleIndexs;//连接顶点的线需要3的倍数,四个顶点需要两个三角形
添加法线
Z轴为负一
Z轴为正一
Z轴为正一
图片的xyz写的不是很好,哈哈哈哈哈哈
Vector3[] tempNormals = new Vector3[4];//顶点有多少个这里就有多少个
tempNormals[0] = new Vector3(0, 0, -1);
tempNormals[1] = new Vector3(0, 0, -1);
tempNormals[2] = new Vector3(0, 0, -1);
tempNormals[3] = new Vector3(0, 0, -1);
CurMesh.normals = tempNormals;//法线是为光照的
添加UV
Vector2[] uvs = new Vector2[4];//UV没有设置的话就会影响贴图
uvs[0] = new Vector2(0, 0);
uvs[1] = new Vector2(0, 1);
uvs[2] = new Vector2(1, 1);
uvs[3] = new Vector2(1, 0);
CurMesh.uv = uvs;//顶点有多少个这个就有多少个
最后
GetComponent<MeshFilter>().mesh = CurMesh;//把创建的网格给指定对象
完整代码
Mesh CurMesh = new Mesh();
CurMesh.name = "CreateMesh";
//为Mesh增加顶点
Vector3[] vectices = new Vector3[4] {
new Vector2(0,0),
new Vector2(0,1),
new Vector2(1,1),
new Vector2(1,0)
};
CurMesh.vertices = vectices;
//连接Mesh里的顶点
int[] TriangleIndexs = new int[6] { 0, 1, 3, 3, 1, 2 };
/* TriangleIndexs[0] = 0;
TriangleIndexs[1] = 1;
TriangleIndexs[2] = 3;
TriangleIndexs[3] = 3;
TriangleIndexs[4] = 1;
TriangleIndexs[5] = 2;*/
CurMesh.triangles = TriangleIndexs;
//为Mesh增加法线
Vector3[] tempNormals = new Vector3[4];
tempNormals[0] = new Vector3(0, 0, -1);
tempNormals[1] = new Vector3(0, 0, -1);
tempNormals[2] = new Vector3(0, 0, -1);
tempNormals[3] = new Vector3(0, 0, -1);
CurMesh.normals = tempNormals;
Vector2[] uvs = new Vector2[4];
uvs[0] = new Vector2(0, 0);
uvs[1] = new Vector2(0, 1);
uvs[2] = new Vector2(1, 1);
uvs[3] = new Vector2(1, 0);
CurMesh.uv = uvs;
GetComponent<MeshFilter>().mesh = CurMesh;