首页 > 技术文章 > Unity3D:改变GameObject的mesh

makebetter 2017-04-22 17:40 原文

1.只能重新生成新的mesh,重新赋值

2.生成的mesh,必须按照官网文档,同时指定:顶点与三角形的index数组,否则不行的

a) assign vertices
b) assign triangles.

3.例子:用代码生成mesh为指定size的cube:

	GameObject createCube (Vector3 meshBoundSize)
	{
		GameObject go = GameObject.CreatePrimitive (PrimitiveType.Cube);
		Mesh mesh = new Mesh ();
		float x = meshBoundSize.x / 2;
		float y = meshBoundSize.y / 2;
		float z = meshBoundSize.z / 2;
		mesh.vertices = new Vector3[] {   
			new Vector3 (-x, -y, -z),  
			new Vector3 (x, -y, -z),  
			new Vector3 (x, y, -z),  
			new Vector3 (-x, y, -z),  

			new Vector3 (-x, y, z),  
			new Vector3 (x, y, z),  
			new Vector3 (x, -y, z),  
			new Vector3 (-x, -y, z),
		};  

		//anticlockwise 
		mesh.triangles = new int[] {  
			3, 1, 0,  
			3, 2, 1,  
			2, 3, 4,  
			2, 4, 5,  
			7, 5, 4,  
			7, 6, 5,  
			0, 6, 7,  
			0, 1, 6,  
			3, 7, 4,  
			3, 0, 7,  
			1, 5, 6,  
			1, 2, 5  
		};  
		mesh.RecalculateNormals ();
		mesh.RecalculateBounds ();

		go.GetComponent<MeshFilter> ().mesh = mesh;

		Material material = new Material (Shader.Find ("Transparent/Diffuse"));
		Color color = Color.red;
		color.a = 0.2f;
		material.SetColor ("_Color", color);

		MeshRenderer renderer = go.GetComponent<MeshRenderer> ();
		renderer.sharedMaterial = material;

		return go;
	}

  

 

推荐阅读