- Home /
How to detect a single collision when 2 identical gameobjects collide.
I have 2 identical gameobjects. When they collide i need to destroy both of them and instantiate the particle system which has an explosion effect. if have code like this on both gameobjects
void OnTriggerEnter2D(Collider2D other) { if(other.gameObject.tag == gameObject.tag) { Instantiate(explosion, gameObject.transform.position, Quaternion.AngleAxis(0f, Vector3.forward)); Destroy(gameObject); }
What I need to change to make method instantiate is called once, not two times.
Answer by Hellium · Mar 21, 2017 at 03:06 PM
You will have to think about a way to "prioritize" your instances, meaning, one must have an "advantage" over the other in order to instantiate your prefab.
You can do your own system, but in your case, I suggest you using the GetInstanceID function which returns and integer representing the instance id of the object, guaranteed to be unique.
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == gameObject.tag)
{
// Only the one with the greater instance ID will instantiate the prefab
if( other.gameObject.GetInstanceID() < gameObject.GetInstanceID() )
{
Instantiate(explosion, gameObject.transform.position, Quaternion.AngleAxis(0f, Vector3.forward));
}
Destroy(gameObject);
}
}
Your answer
Follow this Question
Related Questions
Invisable Projectile; Instantiate at Collisions 2 Answers
How to create detonation time for grenade projectile. 0 Answers
How do I destroy the object that was instatiated 1 Answer
How do I Destroy a Child after Instantiating it? 1 Answer
how to destroy a object only in game and not the prefab 2 Answers