Make a gameObject observe and compare a value on multiple gameObjects around it?

Viewed 249

Let's say I have a board of pegs that never move, and a disc is dropped from the top, Plinko style. As the disc falls and hits pegs, they generate a random value from 1-6, which is displayed on the peg. Now I want each peg that has a direct neighbor with a matching value to turn purple, like so:

enter image description here

I've attached a game object to each peg called Neighbor Checker, and attached circular colliders as triggers that overlap with their neighbors, like so:

enter image description here

The Neighbor Checker game objects attached to the pegs are setup with a circular collider set as a trigger, and a rigid body 2d set to kinematic, discrete collision detection, and never sleep (this continuous checking seems to make the value checking more accurate, but kills performance and the disc falls and bounces all choppy).

The primary problem that I'm having is accuracy: sometimes 3 or 4 pegs are all neighbors with the same value and one will still be green.

I'm using OnTriggerStay2D (Collider2D neighbor) in the neighbor checker script to monitor the values of the pegs and their neighbors, and changing their colors when the values match, like so:

 void OnTriggerStay2D (Collider2D neighbor) {

         if (neighbor.gameObject.tag == "NeighborChecker") {
             textMesh = transform.parent.gameObject.GetComponentInChildren<TextMesh>();
             neighborTextMesh = neighbor.transform.parent.gameObject.GetComponentInChildren<TextMesh>();
             if (textMesh.text == neighborTextMesh.text) { // Make it purple
                 transform.parent.GetComponent<SpriteRenderer>().color = new Color(.5f,0f, 0.5f);
             } 
             else { // Change it back to the original green starting color
                 transform.parent.GetComponent<SpriteRenderer>().color = startingColor;
             }
         }
     }

Any suggestions on how to increase the accuracy and efficiency here? Am I going about this totally wrong? I've seen this in the Unity docs: Physics2D.OverlapCircleAll, and wonder if I should use this at the start to generate a list of neighbors for each peg, then in update loop through these and check their values, but that might get expensive too so I'm not sure.

This is my first 2D unity project. I was ok with the text based stuff, but the physics is kind of hard to grok even though I've read the documentation inside and out! Any help and suggestions would be greatly appreciated.

Thanks in advance!

1 Answers
Related