- Home /
One triggered event to take place between two trigger colliders?
I'm making a very simple RTS. I have a prefab called "Unit" that has a trigger collider on it. The unit also has an enum property called Team. My aim is to make it so that when two units that are not on the same team touch each other they each do a dice roll. The winner of the dice roll "levels up" and the loser is eliminated.
I have a very simple method setup inside OnTriggerEnter() that executes this functionality but the problem I'm having is that both units execute this upon collision, so the event is triggered twice. I don't know of a way to only have this triggered once.
Any suggestions?
Answer by OncaLupe · Nov 23, 2015 at 06:33 PM
Idea 1: On creation, each object gets a unique ID. Simplest way is to just have them do a Random.Range. If you want to be sure of no duplicates, use a manager object to store/generate the IDs. When the units touch, the object with the higher ID runs the code.
Idea 2: Unity is a single thread engine, so one OnTriggerEnter will run before the other. Have that one run the code then set a bool in the other to ignore the event. To make sure of no weird issues, also have it start a coroutine in the other unit that waits for end of frame and set the bool back. If multiple collisions are possible in one frame (three units hitting each other), instead of a bool, add the unit to a list on the other unit to ignore and clear that at end of frame.
Your answer
Follow this Question
Related Questions
Trigger or Colission not work if inside volume 2 Answers
Detecting Trigger Collision for Mecanim Animator 0 Answers
Trigger script does not work. 1 Answer
move camera when it collides with a trigger 1 Answer
Detect Collision in an If Statement? 1 Answer