Unable to create a coloured mesh on a canvas.
I've spent most of today trying to draw between 1 and 4 little red triangles on my main UI canvas (ScreenSpace:Overlay), by using CanvasRenderer and a simple script to designate the triangles. Depending on the shader I can either get invisible triangles (any shader except vertex shader) or pitch black ones (vertex shader). The triangles are in the right place and face the right way but refuse to be coloured. The script that generates the triangles is on the same gameObject as a mesh filter and a CanvasRenderer, and this is the code:
Mesh msh;
GetComponent<MeshFilter>().mesh = msh = new Mesh();//
vertices = new Vector3[max + 1];//outside corners and 0
Color32[] cols = new Color32[max + 1];
Color[] cols0 = new Color[max + 1];
triangles = new int[3 * max];
int vCount = 0;
int tCount = 0;
for (float i = 0; i < max; i++) {//this just sets colours and 0-max (0-4) vertices that form a square.
cols[Mathf.FloorToInt(i)] = new Color32(1, 1, 1, 1);
cols0[Mathf.FloorToInt(i)] = new Color(1, 1, 1, 1);
vertices[vCount++] = 100 * Vector3.up * Mathf.Cos((i / max) * 2 * Mathf.PI) + 100 * Vector3.right * Mathf.Sin((i / max) * 2 * Mathf.PI);
}
vertices[vCount] = Vector3.zero;//final vertex at the centre
cols[vCount] = new Color32(1, 1, 1, 1);
cols0[vCount] = new Color(1, 1, 1, 1);
for (int i = 0; i < max; i++) {
triangles[tCount++] = i; //clockwise to draw
triangles[tCount++] = (i + 1) % (max);
triangles[tCount++] = max;
}
msh.vertices = vertices;
msh.triangles = triangles;
msh.colors32 = cols;
msh.colors = cols0;//this doesn't help, but at least I tried
Vector2[] uvs = new Vector2[vertices.Length];//don't think this matters
for (int i = 0; i < uvs.Length; i++) {
uvs[i] = new Vector2(vertices[i].x, vertices[i].y);
}
msh.uv = uvs;
msh.RecalculateNormals();//its on canvas, why does it need a normal
msh.RecalculateTangents();
transform.GetComponent<CanvasRenderer>().materialCount = 1;
transform.GetComponent<CanvasRenderer>().SetMaterial(mt, 0);
transform.GetComponent<CanvasRenderer>().SetColor(new Color32(1, 1, 1, 1));
transform.GetComponent<CanvasRenderer>().SetMesh(msh);`
Any help would be much appreciated, I've spent hours today making basically no progress on this.
Answer by Cruxifo · May 25, 2018 at 10:49 PM
Dear Cruxifo of 43 minutes ago. We double-checked every default shader and it works okay with the shader unlit/color. Don't ask why. Let's just enjoy it, and never touch that code again.
Your answer
Follow this Question
Related Questions
How to make mesh render objects overlay UI? 1 Answer
How can I change the UI button color when clicked 1 Answer
Canvas Error - Everything tinted blue 2 Answers
Change button color to intermediate value on onclick() event 1 Answer
How can I check if there is no free space in the Text component? 1 Answer