Detecting a string of collisions

I’m making a game, where if 4 balls of a certain colour touch, they all get destroyed. I know how to use OnCollisionEnter() for 2 of the balls touching, or even 3. But if you imagine a line of 4 balls touching

OOOO
1 2 3 4

The first ball and the last ball arn’t touching so OnCollisionEnter() won’t work.
Any advice would be apprechiated. Many thanks,

Burnleyboy101

You should create a class that describes a collision (say, MyCollisionClass)of multiple objects. Most easily implemented by maintaining a list of GameObject with functions to add and remove objects from the collision.

Now, each object will know which collision they’re a part of, so any new colliders can just add themselves to that collision in OnCollisionEnter(). I set the collision class to null when exiting the collision, but a better design decision would be to use the null object pattern.

public MyCollisionClass{
/*
This class contains the list of GameObjects currently 
engaged in the collision. There should also be a way to
add/remove GameObjects from the list. I suggest making a
wrapper for the normal list functions.
*/
}

public class MyCollider : MonoBehaviour{
    MyCollisionClass currentCollision = null

    void OnCollisionEnter(Collision col){
        //you'll need null checks here too
        currentCollision = col.gameObject.GetComponent< MyCollider >().currentCollision
        currentCollision.Add(this.gameObject);
    }

    void OnCollisionExit(Collision col){
        currentCollision.Remove(this.gameObject);
        currentCollision = null;
    }
}

You don’t really explain your use case, but this will allow you, for example, to count how many objects are in a collision or gain access to each individual object that makes up that collision. If you need to know each collision, I would make a private static list of MyCollisionClasses inside MyCollisionClass in which each currently active collision is kept.