- Home /
OnTriggerStay, add the mass of all objects inside the trigger together
Hi,
I'm using a trigger for a set of scales, where if the mass of all the objects inside the trigger is above a certain value, the scales tip. However, I can't figure out how to get add the mass of all objects inside the trigger.
At first I used OnTriggerEnter and OnTriggerExit to add or deduct the mass of each item that was added to the scales. However, due to the code I have for moving objects making the rigidbodies not detect collisions, the Enter code worked, but the Exit code was never activated, meaning the weight stayed the same even when objects were removed. This is something I'm unwilling to change.
So I tried to use OnTriggerStay instead, but I don't know how to get the mass of all the objects inside the trigger instead of just one. Here'smy current code:
function OnTriggerStay (other: Collider){
if (other.transform.rigidbody){
//scaleWeight = scaleWeight + other.transform.rigidbody.mass;
scaleWeight = other.transform.rigidbody.mass;
Debug.Log (scaleWeight);
}
}
When I used this code with 2 objects inside the trigger (weighing 1 and 2 respectively), it only registered the object which weighed 2. I kinda knew it would do so (as there is not actual adding going on here), but I can;t figure out how to write the code to add together all objects found. Would I use some sort of loop?
The blanked out script constantly added to the total mass every frame until it reached ridiculous proportions.
What about using a GetComponent Script, getting all the rigidbody masses, and then using that?
Answer by xCRKx TyPHooN · Apr 26, 2011 at 07:02 PM
When you have an object enter the trigger, add it to a list and than total the list's mass. This way, you will have a list of objects currently inside the trigger. When they exit the trigger, simply pop them off the list. And I would use OnTriggerEnter and OnTriggerExit with the lists... it eliminates a lot of unnecessary checks you get with OnTriggerStay. I know you said you couldn't get it to work, but I don't see how you are going to manage to subtract objects that leave the trigger without an exit function...