Search Unity

String Array isn't going over 5 strings?

Discussion in 'Scripting' started by pilchardDev, Sep 20, 2017.

  1. pilchardDev

    pilchardDev

    Joined:
    Aug 20, 2016
    Posts:
    40
    Hello, I've got a slight issue. When I attempt to make a string array that is 6 or over it give me an " IndexOutOfRangeException: Array index is out of range. " error.
    Code (CSharp):
    1. public string[] weaponStats = {"0", "0", "0", "0", "0", "false"};
    2. private void Start()
    3.     {
    4.         weaponStats[0] = "10";
    5.         weaponStats[1] = "0";
    6.         weaponStats[2] = "0";
    7.         weaponStats[3] = "0";
    8.         weaponStats[4] = "0";
    9.         weaponStats[5] = "0";
    10.     }
     
  2. unit_nick

    unit_nick

    Joined:
    Jul 15, 2017
    Posts:
    23
    Arrays aren't dynamic by nature. They are the size they are declared with. You have declared your array with a range of 6 items which is equivalent to
    Code (csharp):
    1. public string[] weaponStats = new string[6];
    therefore weaponStats[6] would be the 7th item and would return your error.
     
  3. unit_nick

    unit_nick

    Joined:
    Jul 15, 2017
    Posts:
    23
    I will also add the it looks like you would be better off with an int array because you seem to be storing numbers. Note that int 0 will evaluate to false if checked logically.
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Depending on what you need it for, might consider a list instead if you need to be able to add and remove. If not, then you'll just have to set up your array and initialize it with the size you need.