- Home /
Why isn't OnTriggerEnter() called in the beginning of the game?
I am making a game where I detect enemies using OnTriggerEnter()
event and then add them to a list. The problem is that when I place enemies within the trigger collider in the starting of the game, the event isn't triggered. I have tried placing the enemy far and then making the player enter the collider, which works. So, I think the problem is that the Trigger Enter event isn't called in the starting.
Is there a way to trigger the event somehow?
If not is there a work around?
Answer by Vicarian · Jun 08, 2018 at 05:03 PM
TriggerEnter only occurs when an object moves into a trigger volume from outside. You could consider using OnTriggerStay() with a boolean flag to make sure it only gets added once. Be sure to clear it OnTriggerExit(). You could also initialize the lists (serialize them or make them public) and drag the enemies to the relevant lists.
I tried to add the boolean flag, but the problem is that there is not just a single player to be detected, there are multiple objects in the player $$anonymous$$m. So, this way only one of the enemies is detected not all and I don't find another way unless i tell it how many enemies are there.
Adding the enemies manually is a good choice but it should be the last choice. I want the code to be such that it is easier to create more levels without actually telling the AI about the enemies.