- Home /
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).
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.
This is mostly true, but I'm not sure it would cause this particular problem. Writing to the physics system (e.g. creating or moving objects) usually needs to occur in FixedUpdate, but for reading (e.g. raycasts) it shouldn't matter. If you're raycasting in Update, you might get the same result you got last Update, but it shouldn't fail outright.
Answer by AlwaysSunny · May 14, 2017 at 10:22 PM
Be sure this script has not been added to multiple objects. That could easily cause the output you're reporting.
This is most likely the reason so i converted the comment into an answer.
Sorry AlwaySunny, I would have replied earlier but I wasn't able to log in for a couple days - this was indeed the problem, I had errantly added the script as a Component to another GameObject.
Answer by chendryx_disney · May 18, 2017 at 11:04 AM
@AlwaysSunny - yup that's the ticket, I had accidentally added the script to another GameObject. Thanks!
Your answer
Follow this Question
Related Questions
Vector3.Movetoward. Why does this work? 0 Answers
Multiple Cars not working 1 Answer
AI Shooting for Aircraft 1 Answer
using A* pathfinding to go to player after raycast has seen it - c# 0 Answers