triangle selection

I’m working with custom-built meshes and need to select faces with mouse. Mesh is created from file similar to OBJ, where faces can be more than 3 vertices. Such faces I triangulate by myself. Also I show edges of the faces. What I want is when user click on the face, color its edges in different color. I get selected triangle, then find face that contains its vertices, then find edges of this face, and color them. Everything works besides that selected triangle is almost always wrong. I even tried to build a simple cube in this way, and even there are some errors. Any ideas why triangle selection doesn’t work properly?

void OnMouseUp()
{
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    	RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
		{
# clear edge colors
			for( int i = 0; i < m_edgePoints.Count; i++ )
				m_edges*.GetComponent<LineRenderer>().renderer.material.color = Color.red;*

*# find vertices of the triangle hit *

  •   		Mesh m = (hit.collider as MeshCollider).sharedMesh;*
    

_ Vector3 vertices = new Vector3[3] { m.vertices[m.triangles[3 * hit.triangleIndex]],_
_ m.vertices[m.triangles[3 * hit.triangleIndex + 1]], m.vertices[m.triangles[3 * hit.triangleIndex + 2]]_

  •   		};*
    
  •   		Debug.Log( string.Format("Triangle: {0}; {1}; {2}", vertices[0], vertices[1], vertices[2] ) );*
    
  •   		# find selected face*
    
  •   		foreach( var face in m_faces )*
    
  •   		{*
    
  •   			if( face.Contains( vertices[0] ) && face.Contains( vertices[1] ) && face.Contains( vertices[2] ) )*
    
  •   			{*
    
  •   				Debug.Log( "face: " + string.Join( "; ", ( from v in face select v.ToString() ).ToArray() ) );*
    

# color edges of the face

  •   				for( int i = 0; i < m_edgePoints.Count; i++ )*
    
  •   				{*
    

if( face.Contains( m_edgePoints[0] ) && face.Contains( m_edgePoints*[1] ) )
_ {_
m_edges.GetComponent().renderer.material.color = Color.blue;
Debug.Log( string.Format( “Edge: {0}; {1}”, m_edgePoints[0], m_edgePoints[1] ) );
_ }
}
break;
}
}
}
}*_

ok, this was due to MeshCollider.convex = true. If anyone encounters this problem, it should be set to false…

That’s funny, you added the question 2 days ago and I am doing exactly the same thing today.

make sure to look very carefully on Google! These answers pages are awesome they are a veritable encyclopaedia.

I just found this-

it sure avoids using a lot of code!

You might consider changing the UVs of the vertices of the triangle you select, to change the colour. You find a picture with all the colours and with an index you can use to set red blue green, and you set the texture to each pixel that you want the colour of in the UVs, that is a very efficient way to do it for real-time games etc. Because it uses just one texture