Controlling GameObject selection across Parent/Child

Hello all, this is my first question here on UnityAnswers so please bare with me.

Currently I have a GameObject named Board

The Board is comprised of a 20x20 Grid of “Tile” Game objects. Each tile has a C# script that highlights when it is moused over.

I would also like the tiles to be select-able, in that they maintain their highlight if they are clicked by mouse (Additional functionality will be added to this later such as Menu pop ups and building animations).

My problem is a pretty basic one but searching the site I haven’t found a solution, possibly because I am misunderstanding the issue and searching incorrectly.

I do not want more than one “tile” GameObject to be selected at a time.

I.E. If I have tile A selected, and I click tile B, tile B should assume the active selection highlight and tile A should deselect.

I am not sure how to do this via C# script as this script I believe needs to be running on the Board GameObject since it’s the parent object rather than the tiles as children, although I could very easily be wrong. Thank you for any references to where you came up with your answers in advance, and if I missed an answer that could have been found easily via search I do apologize as I did attempt to search before asking.

Without your source, it is difficult to advice a specific solution. The basic idea is to have all the block deselect themselves before processing the new click. There are a number of possible mechanisms for doing this deselection:

Since you are using C#, you can use events and delegates. Here is a tutorial[1]:

[Unity Coding Tips Part 1: Events and Delegates - YouTube][1]

You can use [BroadcastMessage()][2]. Note the script that calls this method does not have to be on the parent. You can do something like:


Assuming a common parent for the tiles, you could walk the transform list:

   foreach (Transform child in transform) {
        child.gameObject.GetComponent< SomeScript >().Deselect();

If you are using Raycasting() (instead of OnMouseDown()) to do the selecting and all the tiles are tagged:

var argo = GameObject.FindObjectsWithTag("tile");
for (int i = 0; i < argo.Length; i++) {
   argo*.GetComponent< SomeScript >().Deselect();*

And I’m sure there are other ways.

[1]: Unity Coding Tips Part 1: Events and Delegates - YouTube
[2]: Unity - Scripting API: Component.BroadcastMessage