GetComponent of Game Objects in an array

Hi, I’m having trouble with the following script:

public class Circle : MonoBehaviour 
{
	public GameObject[] neighbours;

	private Circle circle;

	void Awake ()
	{
		foreach (GameObject neighbour in neighbours)
		{
			circle = neighbour.GetComponent<Circle>();
		}
	}
	
	void OnMouseDown ()
	{
		circle.Toggle();
	}

	void Toggle ()
	{
		// do stuff
	}
}

In my scene is a bunch of circles, each with the Circle script attached. I need each circle to have access to its neighbours, so that when I click on one it toggles it toggles them.

Problem is, with the script above it’s only toggling the last neighbour in the array. How do I GetComponent of each game object in the array?

SendMessage is pretty slow and when possible should be avoided.

In your case, you want each object to toggle its neighbour. Since they all have their neighbour in the Circle script you can use a recursive process:

public Circle neighbour;
public bool toggleOn = false;

public void ToggleNeighbour()
{
   if(neighbour =! null && neighbour.toggleOn == false){
       neighbour.ToggleNeighbour();
   }
}

Same applies if you use an array of Circle, it will only take a little longer since there is more to do.

Other solution is to define a tree of neighbour and use a queue or a stack,
see there for an example unitygems.com - unitygems Resources and Information.