Collision between 2 prefabs with the same script

I’m making a game where there are a bunch of balls bouncing around in a box. All the balls are prefabs and share the same script that will control the logic of what happens when two balls collide. So to start off I tried destroying one of the balls when two of them collide, like so:

void OnCollisionEnter2D(Collision2D coll)
{
	if (coll.gameObject.tag == "Ball")		
		DestroyObject(coll.gameObject);
}

However this destroys both balls since they both get the collision event and both are colliding with a ball. How do I go about deleting one of the balls and ignoring the collision event on the other ball?

You can have them attempt to destroy each other, just have a flag determining which should be destroyed and which should be doing destruction, which can be based on call order. For example:

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

	public bool IsDestroyed = false;
	
	void OnCollisionEnter(Collision collision)
	{
		if (this.IsDestroyed)
		{
			Destroy(this.gameObject);	// or however you want to destroy it.
		}
		else
		{
			Ball otherBall = collision.gameObject.GetComponent<Ball>();
			if (otherBall) otherBall.IsDestroyed = true;
		}
		
	}
}
(of course yours would be collision2D)

You could use Physics2D.IgnoreLayerCollision but some balls at certain point will stop destroying each other because both will ignore collisions.
I think you could change the survived ball layer just after the collision.

How are your balls spawned or created? You could have an ID on your scripts and on instantiate it is +1 of the old one, so balls would have an ID of 1,2,3,4,5,6… And then on the collide get it to check the script of the one it collided with and if it’s ID is higher than it’s own then it destroys itself

This way only 1 ball will exist after a collide but… This means the first ball that is spawned will always survive, you could use a random range to calculate chance

BallStrengh = Random.Range (0, 1000);
If the BallStrengh is lower than the one it collided with then it is destroyed

Public Int BallStrengh;
Private BallScript ScriptRef;

void OnCollisionEnter2D(Collision2D coll)
 {
     if (coll.gameObject.tag == "Ball")
         BallStrengh = Random.Range (0, 1000)
         ScriptRef = coll.GetComponent<BallScript>();
         if (ScriptRef.BallStrengh > BallStrengh) {
             DestroyObject(coll.gameObject);
         }
 }

PS: with this you could also have it check the other balls colour, an easy way I would do it is have strings

Public string CurColour;
Public string ColColour1;
Public string OnColNewColour1;
Public **Classname** TheScriptRef;

TheScriptRef = coll.GetComponent<**Classname**>();

if (TheScriptRef.CurColour = Colcolour1){
CurColour = OnColNewColour1
coll.renderer.material.color = new Color(R, G, B, A);
}