- Home /
A way for a trigger to detect if anything is in it?
Hard to describe what I mean in the title but can you get a trigger to do something if anything is in it. Say that the player is on a space ship with artificial gravity, and if anything enters a trigger in say the power-core then the player gets an upward force to counter gravity. Pretty much you throw something in the core, artificial gravity stops working.
Closest thing I could find is OnTriggerStay but if 20 different objects were in the core wouldn't it be called 20 times throwing the player upward? I know I could get it to set a property to stop gravity but what if there were 1000 or more objects in the core. Seems pretty costly. Is there a simpler way that will be called every frame so long as something remains in the trigger?
Answer by tanoshimi · Sep 10, 2013 at 06:55 AM
Create a Boolean variable called "IsSomethingInTheCore", initialised as false. Do your IsTriggerStay() checks and, if there are any objects within the trigger, set the variable to true. Then, at the end of the update loop, jump the player based on the Boolean value - it won't matter how many objects there were - just that at least one caused it to be set (which I think is what you're describing)
That kind of works but it makes it needlessly difficult when it comes to turning it back off. I guess I could do it at the end of the update function but I'm not sure if unity would do the OnTriggerStay event before or after. That's not my biggest problem anyway.
Say I was using the trigger to detect if there is anything important in an area of a free-roam game (player, AI, bullet, placeable player items etc). Using OnTriggerStay would work until the player goes to the area and and then there are AIs, bullets, player places objects, and all sorts of things everywhere. The trigger would be changing the property for the area maybe 500 times every frame to the same thing. It just seems like there has to be a better way. OnTriggerStay calls what it does every frame for every object in it. I just want a the trigger to call something once every frame so long as something is in it. If there is one thing there it gets called once, and if there are 500 things there it still gets called once.
Even something that I can use in a if statement like SomethingInTrigger would work wonders.
Your answer
Follow this Question
Related Questions
How to dectect Cube (Trigger) is touched 1 Answer
Volume detection. 0 Answers
Detect with Object has been triggered 3 Answers
Can't click gameobject when over another trigger? 1 Answer
Collide with projection 1 Answer