1.概述
Unity自带cube模型,但是此文实现,分基础版和完善版。基础版不进行顶点法线计算,完善版会进行法线计算,结果会跟自带cube比较接近。
2.基础版Cube
2.1 基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))]
public class CreateMeshBase : MonoBehaviour
{
MeshFilter meshFilter;
protected Mesh mesh;
protected virtual Vector3[] Vertices { get; }
protected virtual int[] Triangles { get; }
protected virtual Vector3[] Normals { get; }
protected virtual Vector2[] Uvs { get; }
protected virtual string MeshName { get; }
protected virtual void Start()
{
GetMeshFilter();
}
protected virtual void Reset()
{
GetMeshFilter();
}
protected virtual void OnValidate()
{
GetMeshFilter();
}
void GetMeshFilter()
{
if (meshFilter == null)
{
meshFilter = GetComponent<MeshFilter>();
mesh = new Mesh();
}
mesh.triangles = null;
mesh.uv = null;
mesh.vertices = null;
mesh.name = MeshName;
mesh.vertices = Vertices;
mesh.triangles = Triangles;
mesh.uv = Uvs;
meshFilter.mesh = mesh;
}
private void OnDrawGizmos()
{
if (Vertices == null) return;
Gizmos.color = Color.red;
Gizmos.DrawSphere(Vector3.zero, 0.5f);
Gizmos.color = Color.blue;
for (int i = 0; i < Vertices.Length; i++)
{
Gizmos.DrawSphere(Vertices[i], 0.3f);
}
}
}
2.2 Cube代码
代码即为定义八个顶点,然后依次设置三角形即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateCube : CreateMeshBase
{
public float halfLength = 5;
protected override string MeshName
{
get
{
return "Cube Mesh";
}
}
protected override Vector3[] Vertices
{
get
{
Vector3[] vertices = new Vector3[8];
vertices[0] = new Vector3(-halfLength, -halfLength, -halfLength);
vertices[1] = new Vector3(halfLength, -halfLength, -halfLength);
vertices[2] = new Vector3(halfLength, -halfLength, halfLength);
vertices[3] = new Vector3(-halfLength, -halfLength, halfLength);
vertices[4] = new Vector3(-halfLength, halfLength, -halfLength);
vertices[5] = new Vector3(halfLength, halfLength, -halfLength);
vertices[6] = new Vector3(halfLength, halfLength, halfLength);
vertices[7] = new Vector3(-halfLength, halfLength, halfLength);
return vertices;
}
}
protected override int[] Triangles
{
get
{
int[] triangles = new int[36]
{
0,1,3,
3,1,2,
4,6,5,
4,7,6,
1,6,2,
1,5,6,
0,3,4,
4,3,7,
0,4,1,
1,4,5,
3,2,6,
3,6,7
};
return triangles;
}