I just tried the script from the official unity documentation here https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html , the script is working at some point :
But unity throw error "Array index is out of range" more often than successful click if i click at random place in 1 gameobject ( Cylinder ) :
[ i replay the game and do 5 click , see the error count at the debugger ]
This is my script ( not important it is almost same with the documentation , but i just put it , and i removed some part to make it shorter) :
RaycastHit thehit;
if (Input.GetMouseButtonDown (0) && methodoneenabled == true) {
Ray theray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (theray, out thehit)) {
Debug.Log ("raycast work");
if (thehit.collider != null) {
string thedebug = "Hit : " + thehit.collider.gameObject.name + " ";
MeshCollider themeshhittwo = thehit.collider.gameObject.GetComponent<MeshCollider> ();
if (themeshhittwo == null) {
Debug.Log (" | themeshhittwo == null ! | ");
} else {
Debug.Log (" | " + thehit.triangleIndex + " | ");
Mesh mesh = themeshhittwo.sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3 p0 = vertices [triangles [thehit.triangleIndex * 3 + 0]];
Vector3 p1 = vertices [triangles [thehit.triangleIndex * 3 + 1]];
Vector3 p2 = vertices [triangles [thehit.triangleIndex * 3 + 2]];
Transform hitTransform = thehit.collider.transform;
p0 = hitTransform.TransformPoint (p0);
p1 = hitTransform.TransformPoint (p1);
p2 = hitTransform.TransformPoint (p2);
Debug.Log (" | " + p0 + " ; " + p1 + " ; " + p2 + " | ");
Debug.DrawLine (p0, p1);
Debug.DrawLine (p1, p2);
Debug.DrawLine (p2, p0);
}
}
}
}
My script can be run so tell me if i missed some part when copying and pasting .
Can anyone tell me what is the wrong part and the cause of the error at the script ? -,- though the script is official script ....
Edit : the script i shared is located at CameraScript.Update()
Edit : the error is located at
Vector3 p0 = vertices [triangles [thehit.triangleIndex * 3 + 0]];
but mostly will available at here too
Vector3 p1 = vertices [triangles [thehit.triangleIndex * 3 + 1]];
Vector3 p2 = vertices [triangles [thehit.triangleIndex * 3 + 2]];
Edit : i found out that the error appear if i click the middle of the cylinder , and work well if i click near the corner of the cylinder ( not the corner ! ) , also it is work well at plane mesh without error , but what was causing it -,- .....
vertices.length
withtriangles[thehit.triangleIndex * 3 + 0]
. You will get bigger or the same number, the question is how does it work and why, well here you are just asking to explain a very broad topic of procedural mesh generation and overall mesh construction. Check out some tutorials on this first. – Candid Moon Mar 12 at 16:27