- Home /
Raycast is not hitting a box collider?
My raycast from my camera is not picking up on a box collider I have in my scene. It works fine on a mesh collider, but not the box collider for some reason. Please help! Thanks!
RaycastHit hit;
if (Input.GetKeyDown("mouse 0"))
{
Debug.Log("Smasher");
if (!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit))
return;
MeshCollider meshCollider = hit.collider as MeshCollider;
if (meshCollider == null || meshCollider.sharedMesh == null)
return;
else {
Mesh mesh = meshCollider.sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = 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;
print(p0);
print(p1);
print(p2);
p0 = hitTransform.TransformPoint(p0);
p1 = hitTransform.TransformPoint(p1);
p2 = hitTransform.TransformPoint(p2);
Debug.DrawLine(p0, p1, Color.red);
Debug.DrawLine(p1, p2, Color.red);
Debug.DrawLine(p2, p0, Color.red);
//print(Input.mousePosition);
}
BoxCollider boxCollider = hit.collider as BoxCollider;
if (boxCollider == null)
return;
else {
print("Box hit");
}
Answer by tanoshimi · Feb 07, 2016 at 09:02 PM
That's because of..
MeshCollider meshCollider = hit.collider as MeshCollider;
if (meshCollider == null || meshCollider.sharedMesh == null)
return;
...which broadly translates as "if the raycast hits anything other than a meshcollider, exit this function right now". It'll never get to the bit on line 34 where you test to see if it hits a box collider.
Thank you so much for your reply! So I took that line of code out, and now I get this.
"NullReferenceException: Object reference not set to an instance of an object camControl.Update()"
when I click on something that is not a meshcollider but is a box collider
it points me to line 14 in the code i linked previously
$$anonymous$$esh mesh = meshCollider.shared$$anonymous$$esh;