Phyics.Raycast alternatively returns True/False with static input

I have a script attached to my camera in the FPS Prefab, and in the Update() function I have the following code which effectively shoots a ray from the camera into the world:

bool result = Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward));
Debug.Log(result);

When the Raycast does not hit any colliders in the scene, for example if I’m looking up at the Skybox, Physics.Raycast continuously returns False, which is expected.

However, if I point the camera at a collider in the scene, the raycast alternates between returning True/False, ie on one frame it hits the collider, on the next it doesn’t. This is true even if the camera doesn’t move (ie the input to the Physics.Raycast is identical on every frame).

Be sure this script has not been added to multiple objects. That could easily cause the output you’re reporting.

Any Physics action need be put in the FixedUpdate function not in the Update because any Physics action is only executed in the FixedUpdate, FixedUpdate is called in a interval greater than Update for this reason it is less called, when using in Update in the FixedUpdate frame your code will return true but in other frames the result can change.

@AlwaysSunny - yup that’s the ticket, I had accidentally added the script to another GameObject. Thanks!