MeshFilter meshFilter = (MeshFilter)GameObject.Find( " face ").GetComponent( typeof(MeshFilter));
// 通过渲染器对象得到网格对象
Mesh mesh = meshFilter.mesh;
// API中写的不是提清楚,我详细的在说一遍
// 设置顶点,这个属性非常重要
// 三个点确定一个面,所以Vector3数组的数量一定是3个倍数
// 遵循顺时针三点确定一面
// 这里的数量为6 也就是我创建了2个三角面
// 依次填写3D坐标点
mesh.vertices = new Vector3[] { new Vector3( 5, 0, 0), new Vector3( 0, 5, 0), new Vector3( 0, 0, 5), new Vector3(- 5, 0, 0), new Vector3( 0, - 5, 0), new Vector3( 0, 0, - 5)};
// mesh.vertices = new Vector3[] {new Vector3(5, 0, 0), new Vector3(0, 5, 0), new Vector3(0, 0, 5)};
// 设置贴图点,因为面确定出来以后就是就是2D
// 所以贴纸贴图数量为Vector2
// 第一个三角形设置5个贴图
// 第二个三角形设置一个贴图
// 数值数量依然要和顶点的数量一样
mesh.uv = new Vector2[] { new Vector2( 0, 0), new Vector2( 0, 5), new Vector2( 5, 5)};
// mesh.uv = new Vector2[] {new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1)};
// 设置三角形索引,这个索引是根据上面顶点坐标数组的索引
// 对应着定点数组Vector3中的每一项
// 最后将两个三角形绘制在平面中
// 数值数量依然要和顶点的数量一样
mesh.triangles= new int []{ 0, 1, 2};
我测试时导入了一个立方体,测试时发现导入的立方体顶点是由4*6组成的,也就是说4个点组成一个面,立方体共6个面
顶点是由4*6组成的,但u3d还是会以三角网去解析,关键就是triangles,它负责存储每个三角网的顶点,也就是立方体的一个面由两个三角形组成
Mesh mesh = meshFilter.mesh;
string strVertices = "";
foreach(Vector3 v3 in mesh.vertices){
if (strVertices== ""){
strVertices = v3.ToString();
}
else{
strVertices += " , " + v3.ToString();
}
}
Debug.Log(mesh.vertices.Length + " " + strVertices);
string strUV = "";
foreach(Vector2 v2 in mesh.uv){
if (strUV== ""){
strUV = v2.ToString();
}
else{
strUV += " , " + v2.ToString();
}
}
Debug.Log(mesh.uv.Length + " "+ strUV);
string strTriangles = "";
foreach( int t in mesh.triangles){
if (strTriangles== ""){
strTriangles = t.ToString();
}
else{
strTriangles += " , " + t.ToString();
}
}
Debug.Log(mesh.triangles.Length + " " + strTriangles);
输出的信息如下:
(0.6, -0.6, 0.0),(-0.6, -0.6, 0.0),(0.6, 0.6, 0.0),(-0.6, 0.6, 0.0),
(0.6, -0.6, 0.7),(-0.6, -0.6, 0.7),(0.6, 0.6, 0.7),(-0.6, 0.6, 0.7),
(0.6, -0.6, 0.0),(-0.6, -0.6, 0.7),(-0.6, -0.6, 0.0),(0.6, -0.6, 0.7),
(-0.6, -0.6, 0.0),(-0.6, 0.6, 0.7),(-0.6, 0.6, 0.0),(-0.6, -0.6, 0.7),
(-0.6, 0.6, 0.0),(0.6, 0.6, 0.7),(0.6, 0.6, 0.0),(-0.6, 0.6, 0.7),
(0.6, 0.6, 0.0),(0.6, -0.6, 0.7),(0.6, -0.6, 0.0),(0.6, 0.6, 0.7)
(0.6, 0.1),(0.4, 0.1),(0.6, 0.4),(0.4, 0.4),
(0.4, 0.4),(0.6, 0.4),(0.4, 0.6),(0.6, 0.6),
(0.6, 0.4),(0.9, 0.6),(0.9, 0.4),(0.6, 0.6),
(0.3, 0.7),(0.6, 0.9),(0.6, 0.7),(0.3, 0.9),
(0.6, 0.7),(0.9, 0.9),(0.9, 0.7),(0.6, 0.9),
(0.1, 0.4),(0.3, 0.6),(0.3, 0.4),(0.1, 0.6)
2,0,3,
3,0,1,
5,4,7,
7,4,6,
10,8,9,
9,8,11,
14,12,13,
13,12,15,
18,16,17,
17,16,19,
22,20,21,
21,20,23
可以看出第一个平面是由0,1,2,3这四个点组成,在triangles中指定2,0,3这三个点绘制一个三角网,3,0,1这三个点绘制一个三角网。