- Home /
How to use OnTriggerEnter with multiple triggered objects?
Hey guys! Here's the situation: I have a game in which you place blocks. You have a prespawn block that takes your mouse position. If this block is over another one already placed on the world, you will NOT be able to place it. So no blocks will be over others.
EVERYTHING Is in 2D space! But the prespawn block is over all of the other placed blocks!
Here's what I did: I put a script on the prespawn block that verify if there's a block trigerring it. I put:
public bool onTrigger;
void OnTriggerEnter2D()
{
onTrigger = true;
}
void OnTriggerExit2D()
{
onTrigger = false;
}
void OnTriggerStay2D()
{
onTrigger = true;
}
/*on other script*/
void Update()
{
if(Input.GetMouseButton(0) && !onTrigger) Spawn();
}
Here's the problem: The function OnTriggerExit2D is too fast, so even if the onTrigger is false for one single frame and then true during the other, it placed the block.
2nd problem: If I put 2 blocks one next to the other and I move my prespawn object from the exact position of the 1st block to the other, It will exit the first block's collider to enter the second's one. It's during that frame that onTrigger becomes false when it's not suppose to. So here's the 2nd question: is there a way I can use the OnTriggerExit2D function to set the variable onTrigger ONLY when there's absolutly NO block triggering? It will be really usefull!
Thanks
Answer by AndresBarrera · Jan 19, 2015 at 08:47 AM
Try these two things:
Use FixedUpdate instead of Update, because OnTrigger events are updated at the same rate that physics events.
Keep a count of triggers, and only Spawn when the count is 0
public bool onTrigger; public int triggerCount = 0;
void OnTriggerEnter2D() { onTrigger = true; triggerCount++; }
void OnTriggerExit2D() { onTrigger = false; triggerCount--; }
Will definitly try this! Thanks! And what's the rate of the physics update? And does that means Fixed Update is faster or slower than Update?
It depends on different settings and the device running the game. FixedUpdate should execute at a constant rate (I think you can specify it on the physics settings for your project), while Update can execute at different rates, depending on how many frames per second are being processed
Oh ok, that's nice! So by using it, I'm sure it won't get to fast ;) Seriously, big thanks!