I’ve got some editor-script code where you mouseclick in the scene view, and it uses RaycastHit.triangleIndex to highlight the triangle you hit. But in a new scene, it’s often choosing the wrong triangle - usually a triangle connected to the one clicked. Sometimes it even has two triangles where clicking on one always selects the other. Any ideas what could cause this?
The one special thing about this scene (that I wouldn’t think would be the problem), the objects I’m selecting are all just one giant single mesh, with no submeshes, spread across multiple separate (non-contiguous) parts. Note however that the highlighted triangle has always been on the same part I clicked on, just the wrong triangle.
Code for the mouse click:
static void PathDebugBoundariesGUI(SceneView sceneView)
{
Event cur = Event.current;
if (cur.type == EventType.MouseDown && cur.button != 2)
{
RaycastHit[] hits;
Ray clickRay = HandleUtility.GUIPointToWorldRay(cur.mousePosition);
hits = Physics.RaycastAll (clickRay);
if (hits.Length > 0)
{
foreach (RaycastHit hit in hits)
{
if (hit.collider.name.ToLower ().Contains ("path"))
{
GetTriangleVerticesFromRaycast (hit);
SceneView.RepaintAll ();
break;
}
}
}
}
}
Code that gets the triangle from the mesh:
static void GetTriangleVerticesFromRaycast(RaycastHit hit)
{
Mesh mesh = (hit.collider as MeshCollider).sharedMesh;
if (mesh != null)
{
int[] triangles = mesh.triangles;
Vector3[] vertices = mesh.vertices;
Transform hitTrans = hit.collider.transform;
patherTool_.firstObject_[0] = hitTrans.TransformPoint (vertices [triangles [hit.triangleIndex * 3 + 0]]);
patherTool_.firstObject_[1] = hitTrans.TransformPoint (vertices [triangles [hit.triangleIndex * 3 + 1]]);
patherTool_.firstObject_[2] = hitTrans.TransformPoint (vertices [triangles [hit.triangleIndex * 3 + 2]]);
}
}
Code that highlights the triangle:
if (firstObject_[0] != Vector3.zero)
{
Debug.DrawLine(firstObject_[0], firstObject_[1], Color.magenta);
Debug.DrawLine(firstObject_[1], firstObject_[2], Color.magenta);
Debug.DrawLine(firstObject_[2], firstObject_[0], Color.magenta);
}