# What is the correct way to raycast on click?

I am using raycast from screen point to detect if the user has clicked/touched on something.

The following fails 1/10 times; at first I thought due to the raycast missing the subject below, but after adding in the drawline i realise that it randomly doesn't even fire:

// layerMask declared with correct layers
void FixedUpdate(){
if(Input.GetMouseButtonDown(0)){
Debug.Log("click");
Ray ray;
RaycastHit hit;
if(Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)){
Debug.Log("You clicked on " + hit.collider.gameObject.name,hit.collider.gameObject);
}
}


If I run this in Update() function instead, it will work perfectly - so FixedUpdate() seems to understandably cause the missed clicks... but i'm told I should always run the raycasts in FixedUpdate() for physics optimisation.

Maybe I should split this basic action over 2 functions?

A friend said i need an event handler

• i'm told I should always run the raycasts in FixedUpdate() for physics optimisation. where'd you see that? not necessarily disagreeing, but I've never heard that – jhocking Feb 3 '15 at 22:36
• most tutorials that I have seen regarding raycasts. consider these answers for a similar topic: forum.unity3d.com/threads/physics-raycast-misses-randomly.92221 I guess object positions get updated each physics frame, so if you were raycasting against a G.O. during render frame it might miss. Then fixedupdate runs special optimisations for it's calculations too (likely comparing layers, movement and such) – Hicsy Feb 3 '15 at 22:56

• My understanding is (in Unity) Raycasting against a gameobject's collider for detection IS a physics function though (hence the FixedUpdate()), But I think you are saying it IS recommended I split this basic click+detection over 2 functions then? – Hicsy Feb 3 '15 at 22:26