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. Dismiss Notice

Resolved Iterate through gameobject names to set several similar named active / inactive

Discussion in 'Scripting' started by ralf_b, Sep 3, 2021.

  1. ralf_b

    ralf_b

    Joined:
    Jul 9, 2013
    Posts:
    48
    Hello everybody,

    although I suppose this is an easy one for someone whom is not an autodidact ;) I could not find the right terms to google to find an answer.

    Situation:
    I do have several game objects referenced in a class
    public GameObject btn_video_0;
    public GameObject btn_video_1;
    public GameObject btn_video_2;
    ...

    Goal:

    I would like to set some of them active, always starting with 0 but ending at several different increments which are defined by the length of an array.

    Current Idea:
    I thought the easiest would be to go through a for loop depending on the length of that array, but for obvious reasons this does not work.
    Code (CSharp):
    1.  
    2. for (int i = 0; i < array.Length; i++) {
    3.     btn_video_[i].SetActive(true);
    4. }
    5.  
    Do you have any ideas?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    Instead of having several named variables like:

    Code (CSharp):
    1. public GameObject btn_video_0;
    2. public GameObject btn_video_1;
    3. public GameObject btn_video_2;
    You should just have one array instead:
    Code (CSharp):
    1. public GameObject[] videoButtons;
    Then you can do your loop:

    Code (CSharp):
    1. for (int i = 0; i < videoButtons.Length; i++) {
    2.     videoButtons[i].SetActive(true);
    3. }
     
    ralf_b and Kurt-Dekker like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    Everything that Praetor says is spot on.

    Another way is to parent them all to a single GameObject and turn that on/off all at once, if they are fixed in advance.
     
    ralf_b likes this.
  4. ralf_b

    ralf_b

    Joined:
    Jul 9, 2013
    Posts:
    48
    @PraetorBlue A great many thanks for the quick and helpfull answer, this worked like a charm :)

    @Kurt-Dekker unfortunately I need some of them active and some not, otherwise your route would be the easiest for sure, so thank you too ;)