Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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

Discussion in 'Scripting' started by Cineviz-LLC, Sep 14, 2015.

  1. Cineviz-LLC

    Cineviz-LLC

    Joined:
    Mar 10, 2015
    Posts:
    4
    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();
    }
    }
    }
     
  2. Serdan

    Serdan

    Joined:
    Sep 1, 2015
    Posts:
    10
    If "Window" is your monobehaviour, then just use:
    Code (CSharp):
    1. Window[] windows = gameObject.GetComponentsInChildren<Window>();
    That will get you the array that you can then loop through.
    Code (CSharp):
    1.         foreach (var item in windows)
    2.         {
    3.             if(item.WindowType == windowType)
    4.             {
    5.                 item.Open();
    6.             }
    7.             else if(item.gameObject.activeInHierarchy)
    8.             {
    9.                 item.Hide();
    10.             }
    11.         }
     
    Cineviz-LLC likes this.
  3. Cineviz-LLC

    Cineviz-LLC

    Joined:
    Mar 10, 2015
    Posts:
    4
    Worked Perfectly. Thank you