I’m trying to generate at runtime a simple mesh that is composed by many quads. The problem I’m facing is to assign the triangles for each quad. Note that I’m trying to make the mesh as one unique mesh and not many separated quads. There is no problem in generating the vertices and uvs, but I get an out of bounds triangle error. This is the full script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestMesh : MonoBehaviour {
private List<Vector3> verts = new List<Vector3>();
private List<Vector2> uvs = new List<Vector2>();
private List<int> tris = new List<int>();
public int worldWidth = 10;
public int worldHeight = 10;
// Template map
private int[,] worldMap = new int[,]
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1}
};
// Use this for initialization
void Start () {
CreateWorld ();
}
// Assign a new gameobject as mesh container and prep the mesh
void CreateWorld () {
verts.Clear ();
uvs.Clear ();
tris.Clear ();
GameObject o = new GameObject ("WORLD_MESH");
Mesh mesh = new Mesh ();
if (!o.GetComponent<MeshFilter> ())
o.AddComponent<MeshFilter> ();
mesh = o.GetComponent<MeshFilter> ().mesh;
Vector3 p = Vector3.zero;
int i = 0;
for(int x = 0; x < worldWidth - 1; x++) {
for(int y = 0; y < worldHeight - 1; y++) {
p = new Vector3(x * 1,y * 1, 0);
if(worldMap[x, y] != 0)
AddMeshElements(p, i);
i += 6;
}
}
Vector3[] vertices = verts.ToArray ();
Vector2[] uv = uvs.ToArray ();
int[] triangles = tris.ToArray ();
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
if (!o.GetComponent<MeshRenderer> ())
o.AddComponent<MeshRenderer> ();
MeshRenderer mr = o.GetComponent<MeshRenderer> ();
mr.castShadows = mr.receiveShadows = false;
mesh.RecalculateBounds ();
}
// Add mesh elements to the Lists
void AddMeshElements (Vector3 p, int i) {
verts.Add (new Vector3 (0.5f + p.x, 0.5f + p.y, p.z));
verts.Add (new Vector3( 0.5f + p.x, -0.5f + p.y, p.z));
verts.Add (new Vector3(-0.5f + p.x, 0.5f + p.y, p.z));
verts.Add (new Vector3(-0.5f + p.x, -0.5f + p.y, p.z));
uvs.Add (new Vector2 (1, 1));
uvs.Add (new Vector2 (1, 0));
uvs.Add (new Vector2 (0, 1));
uvs.Add (new Vector2 (0, 0));
tris.Add (i);
tris.Add (i + 1);
tris.Add (i + 2);
tris.Add (i + 2);
tris.Add (i + 1);
tris.Add (i + 3);
}
}
As you can see I try to generate quads from a 2d array skipping the values equal to 0. No problem here, the problem I think is on the number of triangles, but I tried to debug it by checking the tris List as public and everything seemed ok.
I’m skipping something simple for sure, but can’t see the problem. Any help is appreciated.