Getting a list of Child Object with a specific "Base" Script attached.

Forgive me if this has already been asked, I have attempted to search for this but I have not found a satisfactory answer. (One that works)

I have a canvas, with a number of game objects, with a script attached. Each of these scripts are inherited from a base class of Window. (I also have IWindow interface)

MainCanvas (WindowManager script)
MainWindow (MainWindow script inherited from Window)
SelectionWindow(SelectionWindows cript inherited from Window)
GameWindow(GameWindow script inherited from Window)
ExitWindow(ExitWindow script inherited from Window)
Some other GameObjects and Stuff I don’t need at this time.

What I am trying to do is
In the window manager script loop through all child objects what have the window script attached.
There has to be a generic way of getting all gameObject’s children with the Window or IWindow interface and nothing else.

What I have is …

Component[ ] windows = gameObject.GetComponentsInChildren(typeof(IWindow)));
for (int index = 0; index < windows.Length; index++)
{
Window win = windows[index] as Window;
if (win.WindowType == windowType)
{
win.Open();
}
else
{
if (win.gameObject.activeInHierarchy)
{
win.Hide();
}
}
}

If “Window” is your monobehaviour, then just use:

Window[] windows = gameObject.GetComponentsInChildren<Window>();

That will get you the array that you can then loop through.

        foreach (var item in windows)
        {
            if(item.WindowType == windowType)
            {
                item.Open();
            }
            else if(item.gameObject.activeInHierarchy)
            {
                item.Hide();
            }
        }
1 Like

Worked Perfectly. Thank you