I have created a plane with a vertex grid on it using the code below. I am trying to set the colours of the grid to a random colour to test. The grid is 60x60 tiles but when I apply my random color array (colors) to mesh.colors I get a ton of overlapping. Using the code below, how can I colour each of my square tiles in my 60x60 grid a random colour of its own?
// This code was built as part of World of Zero: https://youtu.be/iwsZAg7dReM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class GeneratePlaneMesh:MonoBehaviour {
public float size = 1;
public int gridSize = 16;
private MeshFilter filter;
Color[] colors;
// Use this for initialization
void Start() {
filter = GetComponent<MeshFilter>();
filter.mesh = GenerateMesh();
}
// Update is called once per frame
void Update() {
}
Mesh GenerateMesh() {
Mesh mesh = new Mesh();
var vertices = new List<Vector3>();
var normals = new List<Vector3>();
var uvs = new List<Vector2>();
for(int x = 0; x < gridSize + 1; ++x) {
for(int y = 0; y < gridSize + 1; ++y) {
vertices.Add(new Vector3(-size * 0.5f + size * (x / ((float)gridSize)),0,-size * 0.5f + size * (y / ((float)gridSize))));
normals.Add(Vector3.up);
uvs.Add(new Vector2(x / (float)gridSize,y / (float)gridSize));
}
}
var triangles = new List<int>();
var vertCount = gridSize + 1;
for(int i = 0; i < vertCount * vertCount - vertCount; ++i) {
if((i + 1) % vertCount == 0) {
continue;
}
triangles.AddRange(new List<int>()
{
i + 1 + vertCount, i + vertCount, i,
i, i + 1, i + vertCount + 1
});
}
Debug.Log(vertices.Count);
colors = new Color[vertices.Count];
for(int c = 0; c < vertices.Count; c++) {
int rand = Random.Range(0,5);
switch(rand) {
case 0:
colors
= Color.red;
break;
case 1:
colors[c] = Color.cyan;
break;
case 2:
colors[c] = Color.green;
break;
case 3:
colors[c] = Color.black;
break;
case 4:
colors[c] = Color.blue;
break;
case 5:
colors[c] = Color.white;
break;
}
}
mesh.SetVertices(vertices);
mesh.colors = colors;
Debug.Log(mesh.vertices.Length);
mesh.SetNormals(normals);
mesh.SetUVs(0,uvs);
mesh.SetTriangles(triangles,0);
return mesh;
}
}