- Home /
Raycast doesn't register Rigidbody
This exact code (except for the .rigidbody) worked wonderfull when i tried to hit box.colliders with it. Only thing I changed was turning the box.collider into a rigidbody and suddenly it doesn't react at all. Anybody any idea wtf is going on ?
if (Physics.Raycast(transform.position, transform.up, out hit, lookingDistance)){
if (hit.rigidbody){ Debug.Log("Da");}
}
Just for the record, in Unity, you mustn't do this if (hit.rigidbody)
. There has been a lot of debates about it. The thing is Unity has overriden the way null is checked cause for every C# representation of things (rigidbody, collider) there's also a C++ component in the engine. This way of checking for null does not guarantee the C++ component exists. This might be only be true in cases where C++ straight removes objects from memory while the C# garbage collector kicks in some time later. So use if (hit.rigidbody != null)
If that doesn't fix it, the object you're raycasting against does not have a Rigidbody, or you're not even hitting what you're trying to hit.
Answer by Lysander · Jan 02, 2018 at 08:49 PM
A Rigidbody and a Collider are not swappable- they aren't the same thing, they just both have to do with the physics engine. A Rigidbody says "the physics engine should track or control this object, and allow it to interact with other physics objects", while a Collider says "this is the shell that serves as a physics obstacle". A moving object that needs to collide with other objects needs both. A static object that other objects collide with only needs to have a Collider (the other objects need a Rigidbody AND Collider to do the colliding).
A physics raycast doesn't hit Rigidbodies on their own (they have no 'shell' defined to hit), the "RaycastHit" objects they produce just has a shortcut property that's exactly the same as calling GetComponent() on the colliding object. If the hit objects has no Rigidbody, because it's stationary, hit.rigidbody will be null. If an object has a Rigidbody but no Colliders, it cannot collide with anything, and it cannot be hit by raycasts- this is likely only useful for flying objects that need to be affected by physics for visual reasons (like certain special affects), but which don't actually affect anything else in the scene.
Hope that helps!
Thank you very much. I originally thought unity somehow blocked me from using a collider and a rigidbody on the same object, but it seems like I just imagined this cause now it worked like a charm. Sometimes I myself am my worst enemy I guess. Anyway, thanks a lot!
Your answer
Follow this Question
Related Questions
Camera Collision Not Working 0 Answers
How do I pass through certain colliders but detect all collisions? 1 Answer
Player Collision with objects (help) 3 Answers
Smooth rigidbody movement 2 Answers
Prevent player from walking through/pushing walls that are Rigidbodies and have Box colliders 1 Answer