- Home /
Check for rigidbody presence when in collision with a trigger
Hey, I have a setup where a box collider (is Trigger) is in front of the moving character. It follows the mouse and applies a rigidbody.AddForce on any object caught in the trigger.
This is supposed to apply only to props like crates and similar, but it also applies by default to objects without rigidbodies. Hence I get this error:
MissingComponentException: There is no 'Rigidbody' attached to the "platformA_1" game object, but a script is trying to access it. You probably need to add a Rigidbody to the game object "platformA_1". Or your script needs to check if the component is attached before using it. UnityEngine.Rigidbody.AddForce (Vector3 force) (at E:/BuildAgent/work/71ca6fec1b41cc30/Runtime/Export/Generated/NewDynamics.cs:469) fieldBehaviour.OnTriggerStay (UnityEngine.Collider collisionInfo) (at Assets/Scripts/behaviours/hero/fieldBehaviour.js:18)
It doesn't currently affect the game, but I get the ugly error and it interferes with debugging.
Is there any way to filter through the rigidbody.AddForce to only objects with a rigidbody? More specifically, how can I check if the Collider I get from
function OnTriggerStay (collisionInfo : Collider ) {
has a rigidbody attached to it or not?
thanks
Answer by Teare · Apr 23, 2011 at 06:14 PM
Thanks for anyone who viewed the question, but I found an easy solution on my own. The objects' lack of a rigidbody can be filtered out using
if(collisionInfo.rigidbody){
where the statement will only run if the object has a rigidbody attached
If anyone has an alternative I'd love to hear it
Answer by microp · May 11, 2011 at 06:02 PM
Hi! You might also want to look into layers. These could help you cull out unwanted objects and decide for which ones you want to receive collision and trigger callbacks at all (Edit/Project settings/Physics). I think this feature was introduced in Unity 3.0.
Still, your original solution looks very acceptable to me and might actually be easier ot maintain. The layer-based collision matrix can get pretty messy after a while and cause quite a few headaches! :)
Thanks for your comment there. I was actually using an older version of Unity and wasn't aware of the massive amount of updates that came with the newer version.
Your answer
Follow this Question
Related Questions
Why do I get this error in such a simple script? 3 Answers
Simple Triggers problem. 1 Answer
Rigidbody2D alternating between TriggerEnter and TriggerExit? 1 Answer
isKinematic rigidbody collisions 3 Answers
col.gameObject.layer is not working 1 Answer