Unity3D用代码方式创建一个Cube并对其进行操作用C#实现器

首先创建一个MakeCube脚本

在Awake函数中写以下代码

private void Awake()

{

var
pMeshFilter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;//网格过滤器

var
pMeshRender = gameObject.AddComponent(typeof(MeshRenderer)) as MeshRenderer;//网格渲染

var pMesh =
pMeshFilter.mesh as
Mesh;    //网格过滤器的实例化的Mesh

Vector3[] pVector = new Vector3[36];

int[]
pTriangles = new int[pVector.Length];

//forword

pVector[0] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[1] = new
Vector3(-0.5f, 0.5f, -0.5f);

pVector[2] = new
Vector3(0.5f, 0.5f, -0.5f);

pVector[3] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[4] = new
Vector3(0.5f, 0.5f, -0.5f);

pVector[5] = new
Vector3(0.5f, -0.5f, -0.5f);

////back

pVector[6] = new
Vector3(-0.5f, 0.5f, 0.5f);

pVector[7] = new
Vector3(-0.5f, -0.5f, 0.5f);

pVector[8] = new Vector3(0.5f,
0.5f, 0.5f);

pVector[9] = new
Vector3(0.5f, 0.5f, 0.5f);

pVector[10] = new
Vector3(-0.5f, -0.5f, 0.5f);

pVector[11] = new
Vector3(0.5f, -0.5f, 0.5f);

//left

pVector[12] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[13] = new
Vector3(-0.5f, 0.5f, 0.5f);

pVector[14] = new
Vector3(-0.5f, 0.5f, -0.5f);

pVector[15] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[16] = new
Vector3(-0.5f, -0.5f, 0.5f);

pVector[17] = new Vector3(-0.5f,
0.5f, 0.5f);

//right

pVector[18] = new
Vector3(0.5f, -0.5f, -0.5f);

pVector[19] = new
Vector3(0.5f, 0.5f, -0.5f);

pVector[20] = new
Vector3(0.5f, 0.5f, 0.5f);

pVector[21] = new Vector3(0.5f,
-0.5f, -0.5f);

pVector[22] = new
Vector3(0.5f, 0.5f, 0.5f);

pVector[23] = new
Vector3(0.5f,- 0.5f, 0.5f);

//up

pVector[24] = new
Vector3(0.5f,-0.5f, 0.5f);

pVector[25] = new
Vector3(-0.5f, -0.5f, 0.5f);

pVector[26] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[27] = new
Vector3(0.5f, -0.5f, 0.5f);

pVector[28] = new
Vector3(-0.5f, -0.5f, -0.5f);

pVector[29] = new
Vector3(0.5f, -0.5f, -0.5f);

//down

pVector[30] = new
Vector3(-0.5f, 0.5f, -0.5f);

pVector[31] = new
Vector3(-0.5f, 0.5f, 0.5f);

pVector[32] = new
Vector3(0.5f, 0.5f, 0.5f);

pVector[33] = new
Vector3(-0.5f, 0.5f, -0.5f);

pVector[34] = new
Vector3(0.5f, 0.5f, 0.5f);

pVector[35] = new
Vector3(0.5f, 0.5f, -0.5f);

for (int nIndex = 0; nIndex
< pTriangles.Length; ++nIndex)

{

pTriangles[nIndex] = nIndex;

}

pMesh.Clear();

pMesh.vertices = pVector;//网格顶点

pMesh.triangles = pTriangles;//三角形

pMesh.RecalculateBounds();

}

创建一个空物体

把MakeCube脚本挂在空物体上,运行即可。

你可能感兴趣的:(Unity3D用代码方式创建一个Cube并对其进行操作用C#实现器)