Creating multiple faces (cubes)

Hey there!

I skimmed through the “After playing Minecraft” thread and the “Star, a Unity C# Tutorial” tutorial and came up with this code:

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class NewMesh : MonoBehaviour {
private Mesh mesh;

private Vector3[] vertices;
private int[] triangles;
private Vector2[] uv;

private readonly byte size = 16;

void Start()
{
    mesh = new Mesh();
    mesh = createNewMesh(Vector3.zero);
}

Mesh createNewMesh(Vector3 position)
{
    Mesh returnMesh = new Mesh();
    GetComponent<MeshFilter>().mesh = returnMesh;
    returnMesh.name = "Mesh" + position;

    vertices = new Vector3[4] { new Vector3(Mathf.Floor(position.x / size) * size, 0, Mathf.Floor(position.x / size) * size), 
                                new Vector3((Mathf.Floor(position.x / size) + 1) * size, 0, Mathf.Floor(position.x / size) * size),
                                new Vector3(Mathf.Floor(position.x / size) * size, 0, (Mathf.Floor(position.x / size) + 1) * size), 
                                new Vector3((Mathf.Floor(position.x / size) + 1) * size, 0, (Mathf.Floor(position.x / size) + 1) * size) };

    triangles = new int[6] { 0, 2, 1, 1, 2, 3 };

    uv = new Vector2[4] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) };

    returnMesh.vertices = vertices;
    returnMesh.triangles = triangles;
    returnMesh.uv = uv;

    returnMesh.RecalculateNormals();

    return returnMesh;
}
}

Which I then attached to an empty GameObject. It creates a plane at a given position which is aligned to a grid. My questions are: How would I go about creating multiple planes? Is having this script attached to an empty GameObject the best way to do it?

No worries, I’m not trying to re-create Minecraft! Just experimenting.

I would appreciate help!

Lets say you want 100 of these planes you created:

for(int i =0; i < 100; i++)
{
      GameObject g = new GameObject();
      g.AddComponent<MeshFilter>();
      g.AddComponent<MeshRenderer>();
      g.AddComponent<NewMesh>();
}

And its done, as your script auto execute itself its just a case of creating new objects and them put your script on to them.

But the way I’ve done it above you’ll have 100 GameObjects with useless script inside them. I think its better to have a generator that creates objects, add MeshFilter and MeshRender and them change the mesh.