- Home /
How do I make multiple meshes in the same script?
Hi, I am trying to generate a series of planes between markers that the player can place in the game world, I've got code to generate the meshes but the last mesh is the only one that ever shows up, I've tried naming them and tried to set them as different game objects with no success, I was just wondering if anyone could help me out, this is my first C# project so I'm hoping I've just missed something simple:
while (planeNo < markerNo)
{
MeshFilter meshFilter = GetComponent<MeshFilter>();
if (meshFilter == null)
{
print("MeshFilter not found bro!");
return;
}
markerStartX = (GameObject.Find("Marker "+planeNo).transform.position.x);
markerStartZ = (GameObject.Find ("Marker "+planeNo).transform.position.z);
planeNo ++;
markerEndX = (GameObject.Find ("Marker "+planeNo).transform.position.x);
markerEndZ = (GameObject.Find ("Marker "+planeNo).transform.position.z);
Vector3 p0 = new Vector3(markerStartX,0,markerStartZ);
Vector3 p1 = new Vector3(markerStartX,buildingHeight,markerStartZ);
Vector3 p2 = new Vector3(markerEndX,buildingHeight,markerEndZ);
Vector3 p3 = new Vector3(markerEndX,0,markerEndZ);
Mesh mesh = meshFilter.sharedMesh;
//mesh.name = ("Mesh "+planeNo);
if (mesh == null)
{
meshFilter.mesh = new Mesh();
mesh = meshFilter.sharedMesh;
}
mesh.Clear ();
mesh.vertices = new Vector3[]{p0,p1,p2,p3};
mesh.triangles = new int[]
{
0,1,2,
0,2,3,
2,1,3,
0,3,1
};
mesh.uv = new Vector2[4];
mesh.uv[0].x = 0; mesh.uv[0].y = 0;
mesh.uv[1].x = 1; mesh.uv[1].y = 0;
mesh.uv[2].x = 0; mesh.uv[2].y = 1;
mesh.uv[3].x = 1; mesh.uv[3].y = 1;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
meshNo ++;
}
Answer by robertbu · May 23, 2013 at 02:55 AM
What you are doing is taking a single game object and resetting the mesh for that single game object over and over. I'm not sure of your goal here. It is possible to make each of your planes a sub-mesh. Each sub-mesh can have its own material, but you don't gain much else, and it is difficult to code user interaction with sub-meshes.
Instead, if the user is to interact with these planes, I suggest each time through the loop: 1) Create a new game object, 2) Add a MeshFilter component to the game object, 3) Set the plane mesh for that MeshFilter. The results will be a game object per plane.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How can I generate a up facing quad mesh with variable resolution? 0 Answers
SetTriangles does not accept a NativeArray. Best way around this? 1 Answer
Strange Edge Shadows on Generated Flat Mesh 0 Answers
How can I generate a up facing quad mesh with adjustable res? 0 Answers