Hey guys,
I’m really stumped on this one. I’m trying to create a mesh to use as a grid for a tile-world, but I have REALLY screwed up the UV positioning. Can anyone tell me what I’ve done wrong?
using UnityEngine;
using System.Collections;
public class GridScript3 : MonoBehaviour {
public GameObject theObj;
public Material mat;
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*4)];
Vector2[] meshUVs = new Vector2[(sectionsWidth*sectionsHeight*4)];
Vector3[] meshNormals = new Vector3[(sectionsWidth*sectionsHeight*4)];
int[] meshTriangles = new int[3*(sectionsWidth*sectionsHeight)*2];
int verticeIndex = 0;
for(int i = 0; i < sectionsWidth; i++) {
for(int j = 0; j < sectionsHeight; j++) {
vertices[verticeIndex] = new Vector3((float)i, 0f, (float)(j));
vertices[verticeIndex+1] = new Vector3((float)i+1, 0f, (float)(j));
vertices[verticeIndex+2] = new Vector3((float)i, 0f, (float)(j)+1);
vertices[verticeIndex+3] = new Vector3((float)i+1, 0f, (float)(j)+1);
meshUVs[verticeIndex] = new Vector2(0f, 0f);
meshUVs[verticeIndex+1] = new Vector2(1f, 0f);
meshUVs[verticeIndex+2] = new Vector2(0f, 1f);
meshUVs[verticeIndex+3] = new Vector2(1f,1f);
meshNormals[verticeIndex] = meshNormal;
meshNormals[verticeIndex+1] = meshNormal;
meshNormals[verticeIndex+2] = meshNormal;
meshNormals[verticeIndex+3] = meshNormal;
verticeIndex += 4;
}
}
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;
mr.renderer.material = mat;
mesh.RecalculateBounds();
}
// Update is called once per frame
void Update () {
}
}
I know I’ve done something wrong and its probably very obvious. Please be kind