- Home /
OnTriggerEnter, called on both instantiated objects
Hey !
I have several objects in my scene, they're all instantiated randomly, and they have the same scripts, because I instantiate them as a prefab. However, I want my OnTriggerEnter2D to only be called on one of the objects, both objects have same tag and layer.
In OnTriggerEnter2D I want to move one of the gameobjects up or down, otherwise it will look weird with two objects inside each other.
What should I do ?
Any answer is appreciated !
/ Andreas
Answer by tanoshimi · Jul 29, 2014 at 06:43 PM
OnTrigger messages are always sent to both the object with the trigger collider attached, and also the object that collided with it. If you want the behaviour for rach object to differ you'll have to code that inside the OnTrigger callback somehow (on instantiation of each copy of the prefab, you could assign a variable to determine how it should behave in a collision)
Tanoshimi is right.
Think about it this way . . . .
Which object do you want the OnTriggerEnter to be fired on ? The first one ? (which happens to be exactly the same as the second). Which object knows it's the one to fire, and how does it know ?
Solve this problem and you'll know what to do in your OnTriggerEnter()
Answer by LostSheepGames · Aug 01, 2014 at 03:51 PM
The system will have to deal with them one at a time, so give your script a boolean flag, something like public bool triggered
, and have the OnTriggerEnter
do something like this: if (triggered) { triggered = false; return; } Foo foo = other.GetComponent (); foo.triggered = true; //Your movement code here... Where Foo
is the name of the script that contains this OnTriggerEnter
. This will ensure that only one of the colliding objects deals with the collision.