Hey guys! I’m fairly new to unity and I’m working on a project where I’ve created a mesh plane, subdivided into 100x100 quads, each of which I want to texture procedurally with different tiles (i.e. It’s the game map for a top-down tile-based game. From what I’ve gathered, the best way to approach is to doing this is with a texture atlas. Like I said, I’m new to Unity and 3D dev in general, so if anyone could help me with how to get this working, I would be very very grateful.
Here is how I am creating the mesh
public class CreateMesh : MonoBehaviour {
public GameObject theObj;
int sectionsWidth = 100;
int sectionsHeight = 100;
Vector3 meshNormal = Vector3.up;
// Use this for initialization
void Start () {
Mesh mesh = new Mesh();
mesh.name = "testMesh";
mesh.Clear();
Vector3[] vertices = new Vector3[(sectionsWidth*sectionsHeight)];
Vector2[] meshUVs = new Vector2[(sectionsWidth*sectionsHeight)];
Vector3[] meshNormals = new Vector3[(sectionsWidth*sectionsHeight)];
int[] meshTriangles = new int[3*(sectionsWidth*sectionsHeight)*2];
for(int i = 0; i < sectionsWidth; i++) {
for(int j = 0; j < sectionsHeight; j++) {
vertices[j*sectionsWidth + i] = new Vector3((float)i, 0f, (float)(j));
meshUVs[j*sectionsWidth + i] = new Vector2((i/2.0f)/sectionsWidth,(i/2.0f)/sectionsHeight);
meshNormals[j*sectionsWidth + i] = meshNormal;
}
}
int index = 0;
for (int y = 0; y < sectionsWidth-1; y++) {
for (int x = 0; x < sectionsWidth-1; x++) {
// For each grid cell output two triangles
meshTriangles[index++] = (y * sectionsWidth) + x;
meshTriangles[index++] = ((y+1) * sectionsWidth) + x;
meshTriangles[index++] = (y * sectionsWidth) + x + 1;
meshTriangles[index++] = ((y+1) * sectionsWidth) + x;
meshTriangles[index++] = ((y+1) * sectionsWidth) + x + 1;
meshTriangles[index++] = (y * sectionsWidth) + x + 1;
}
}
mesh.vertices = vertices;
mesh.triangles = meshTriangles;
mesh.normals = meshNormals;
mesh.uv = meshUVs;
MeshFilter mf = (MeshFilter)theObj.gameObject.GetComponent(typeof(MeshFilter));
MeshRenderer mr = (MeshRenderer)theObj.gameObject.GetComponent(typeof(MeshRenderer));
mf.mesh = mesh;
mr.renderer.material.color = Color.red;
mesh.RecalculateBounds();
}