Search Unity

Arrays in UI canvas

Discussion in 'Scripting' started by UnaiLz, Sep 7, 2017.

  1. UnaiLz

    UnaiLz

    Joined:
    Dec 12, 2015
    Posts:
    46
    Hi there, everyone!

    I'm trying to make an UI system with canvas, and I thought (based on my skills ) that the best way to make an interface could be something like this:

    Code (CSharp):
    1. public GameObject[] Options;
    2.  
    3.     void Start ()
    4.     {
    5.         for (int i = 0; i <= Options.Length; i++)
    6.         {
    7.             Options [i].SetActive (false);
    8.         }
    9.     }
    10.  
    11.     public void Boton (int iii)
    12.     {
    13.         for (int i = 0; i <= Options.Length; i++)
    14.         {
    15.             Options [i].SetActive (false);
    16.         }
    17.  
    18.         Opciones [iii].SetActive (true);
    19.     }

    My intentions were to make an inspector-editable UI making a public GameObject array to put groups in there and activate and deactivate it by clicking the main buttons, using an int to select which group I wanted to activate on inspector and leaving the rest of them in to SetActive (false).

    The problem is that when the first loop ends, the array goes out of range, and I don't know how to fix it.

    I really don't know if this is the best way to do it, but it was the easiest way that I could think of, but I'm not very good using arrays

    If someone knows a better way to do this (and I'm sure that there has to be ) I'd love to talk about it :)
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Options.Length is out of range because arrays start at 0. Change your loop to i < Options.Length instead of <=
     
    sdutter and UnaiLz like this.
  3. UnaiLz

    UnaiLz

    Joined:
    Dec 12, 2015
    Posts:
    46
    This is just what I needed!!! Thak you ^^