- Home /
Color triangle on mesh
Hi, I'm trying to vertex color every triangle on mesh with random color, but I'm getting this:
but I'm want to get this:
The red triangle is always one-colored and other ones on mesh aren't.
using UnityEngine;
using System.Collections;
public void VertsColor(GameObject gameObject)
{
Mesh mesh = gameObject.GetComponent<MeshFilter>().mesh;
int[] triangles = mesh.triangles;
Vector3[] vertices = mesh.vertices;
Vector3[] verticesModified = new Vector3[triangles.Length];
int[] trianglesModified = new int[triangles.Length];
Color32 currentColor = new Color32();
Color32[] colors = new Color32[triangles.Length];
for (int i = 0; i < trianglesModified.Length; i++) {
// Makes every vertex unique
verticesModified[i] = vertices[triangles[i]];
trianglesModified[i] = i;
// Every third vertex randomly chooses new color
colors[triangles[i]] = currentColor;
if(triangles[i] % 3 == 0)
currentColor = new Color(
Random.Range (0.0f, 1.0f),
Random.Range (0.0f, 1.0f),
Random.Range (0.0f, 1.0f),
1.0f);
}
// Applyes changes to mesh
mesh.vertices = verticesModified;
mesh.triangles = trianglesModified;
mesh.colors32 = colors;
}
Thanks for your help!
Answer by _dns_ · Aug 19, 2014 at 01:41 PM
Hi, I think you have to index with "i" in lines 24 and 25 instead of "triangle[i]" (there "i" is your new vertex + triangle + colors index)
Line24: colors[i] = currentColor;
Line25: if( i % 3 == 0 )
Indeed, though you also need to swap the order of line 24 and the if statement:
if(i % 3 == 0){
currentColor = new Color(
Random.Range (0.0f, 1.0f),
Random.Range (0.0f, 1.0f),
Random.Range (0.0f, 1.0f),
1.0f
);
}
colors[i] = currentColor;
Answer by Owen-Reynolds · Aug 19, 2014 at 01:50 PM
Seems way to specific a Q to be here, but:
In the "every 3rd vert change color," isn't triangles[i] just a randomish number? Try a Debug to see when you change colors.
Shouldn't it be simply if(i%3==0)
? And assign the color afterwards? i.e.: tri indexes 3,4,5 form a tri, so you pick a color for 3, use it for 3,4,5; then pick a new color just before assigning 6,7,8.
Answer by technofeeliak · Oct 17, 2020 at 05:34 PM
This Brackeys video may help. https://www.youtube.com/watch?v=lNyZ9K71Vhc