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.
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);
}
}