Search Unity

Problem initializing array. Noob question.

Discussion in 'Scripting' started by awildryan, May 30, 2019.

  1. awildryan

    awildryan

    Joined:
    Apr 9, 2016
    Posts:
    2
    Hello everyone,

    I was trying to make a simple bag system(kind of like world of Warcraft) with two arrays. the problem I'm having is whenever I try to read information from the array it never reads past i=0.(When the for line reads "for (int i = 0; i < slots.length; i++)") If I change it to I<16 like in the picture it will loop as intended.

    upload_2019-5-30_12-48-24.png

    So I initialized my arrays at the start of this script and then the arrays were to be referenced from another script and it wasn't working so I came back here to try and debug it on my own. The length of the public arrays was set in the unity editor.
    upload_2019-5-30_12-50-46.png

    It was my understanding that "array.length" would get how long the array was as an int. But it always returns 0; I've edited my for loop to say i < 16 and it will run. before, and the way I wanted it to work was i<slots.length, but when I have it like that my for loop does not run.

    Any guidance would be appreciated, I tried to manually set the length of the arrays "bool[] slots = new bool[16]" but that had the same issue. Is it a simple syntax error I am missing? Or am I using the array.length wrong? Or maybe my loop is just wrong.
     
    Last edited: May 30, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Your understanding is correct.

    It is possible you inadvertently dragged your inventory script onto more than one GameObject, or twice on the same Object, and you have only populated one of the instance lists.

    You can type "t:Inventory" (without the quotes) in the Hierarchy window search pane and see if it is on more than one GameObject.

    Another approach is to make an empty scene, put a single object in it, put a single bool and a single GameObject in your arrays and run.
     
  3. awildryan

    awildryan

    Joined:
    Apr 9, 2016
    Posts:
    2
    Hmm. I don't know how or when I did it but I did have the script on two different objects. Thank you for the tip, that is very useful information to have! :)
     
    Kurt-Dekker likes this.