- Home /
Raycast stops working after ~40 seconds when target has Rigidbody
I've encountered a strange problem with raycasting. My player object has a C# component that uses raycasting to detect the nearest item that can be interacted with. I noticed that after approximately 40 seconds, the raycast would stop finding a hit. I've done quite a bit of troubleshooting and discovered that if I remove the Rigidbody attached to the target object, the raycast works fine indefinitely, but when the Rigidbody is present, it always fails in approximately the same amount of time. I've tried all of the "cast" variants (sphere, box, etc.) and they all have the same problem.
Any idea why this is happening? There are many other raycasts occurring elsewhere in the scene and they're working fine. Are there circumstances that prevent the raycasting system from working?
Answer by lcompton · Dec 09, 2020 at 06:46 PM
For those who may run into the same problem, here's the fix. As it turns out, my prefabs had mixed layer definitions. Now that all items in the prefab hierarchies are set to the same layer, the raycasts now work consistently. I can't explain why they worked for a while and then stopped, but that's what I consistently observed on two different computers and with various versions of Unity 2020.1. I hope this helps. Cheers!
Answer by Naiveca · Sep 22, 2021 at 05:37 PM
I had the exact same problem, having mixed layers or not didn't do a thing for me. But, if your implementations of a rigidbody allow it, in the rigidbody inspector there's Constraints and Freezing the position of the rigidbody in every axis fixed the issue for me. In my case, I only use the rigidbody to check for collisions with a sphere collider, so I don't need it to move.
My guess is that when gravity is getting applied to the rigidbody, it falls down even though you wouldn't see it move (this can be checked with object.velocity), the Y axis keeps going negative even though the gameobject wouldn't move. When the rigidbody falls enough, it becomes impossible to hit with a raycast, even though I don't know how this affects the colliders, as they are in the same position as before.