I would like to change the color of a mesh triangle when I click on it. The following code is not working. When I draw a debug line then the correct triangle is highlighted, but the color is not changed. What am I missing here?
void HighlightTriangle2()
{
if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
return;
}
MeshCollider meshCollider = hit.collider as MeshCollider;
if (meshCollider == null || meshCollider.sharedMesh == null)
{
return;
}
Debug.Log("hit.triangleIndex = " + hit.triangleIndex);
mf.mesh = meshCollider.sharedMesh;
Vector3[] vertices = mf.mesh.vertices;
int[] triangles = mf.mesh.triangles;
Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
Transform hitTransform = hit.collider.transform;
p0 = hitTransform.TransformPoint(p0);
p1 = hitTransform.TransformPoint(p1);
p2 = hitTransform.TransformPoint(p2);
//Debug.DrawLine(p0, p1, lineColor, duration);
//Debug.DrawLine(p1, p2, lineColor, duration);
//Debug.DrawLine(p2, p0, lineColor, duration);
int v1 = hit.triangleIndex * 3 + 0;
int v2 = hit.triangleIndex * 3 + 1;
int v3 = hit.triangleIndex * 3 + 2;
colorArray[v1] = Color.red;
colorArray[v2] = Color.red;
colorArray[v3] = Color.red;
mf.mesh.colors = colorArray;
}
I am creating the mesh as follows. The mesh is a cube with 24 vertices. I am using a legacy VertexLit shader. The color is not changed though.
private void CreateMesh()
{
Mesh mesh = new Mesh();
mesh.Clear();
List<Vector3> vertList = DoVertices();
mesh.SetVertices(vertList);
List<int> trisList = DoTriangles(vertList);
mesh.SetTriangles(trisList, 0);
List<Vector2> uvsList = DoUVs_TEST();
mesh.uv = uvsList.ToArray();
MeshRenderer mr = GetComponent<MeshRenderer>();
mr.material = defaultMaterial;
Color[] colorArray = new Color[mesh.vertices.Length];
for (int k = 0; k < mesh.vertices.Length; k++)
{
colorArray[k] = Color.white;
}
mesh.colors = colorArray;
mf.mesh = mesh;
}
mf.meshas well. See the documentation on how these 'mesh' properties behave.mesh.verticesevery time returns a new copy array ... you for sure do not want to access this multiple times just to obtain the length - instead rather use thevertList.Count... in general you might even want to detach the triangle and use a new one in order to not get color bleeding on the edges ... see e.g. stackoverflow.com/questions/57423218/…