Can I select a variable from an array using a variable? Javascript

Hello, I have searched up and down google trying to figure out whether I can get one of the array values by using a variable. I looked at the docs and they didn’t address it, the array unity tutorial was in c# and my searches proved unfruitful. If I overlooked something, I am very sorry

My code:

private var slot : GUITexture
private var activeSlot : int;

function Start(){

    var slots = new Array();

    slots.Add(slot);
    slots.length = 24;

}

function AddItem(){

    if(activeSlot <= 25){
         slots[activeSlot] = logs;
    }
}

I’m on my phone so I’ll just post the issue, not the entire code
The above code throws the error BCE0005: Unknown identifier: ‘slots’.

To start, yes you can use a variable to index into an array. As for your code, there are three major issues:

  1. Do not use the Array class. It is untype, and slow, and anything you can do with it can be done better with other classes. If your array is fixed size, use the built-in array. If your array needs to vary in size use when of the .NET collections like the generic List class. More information on the various collections can be found here:

http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F

It looks like you want a built in array, so you will want something like:

 var slots : GUITexture = new GUITexture[24];
  1. You are declaring your ‘slots’ variable inside of Start(). Any variables declared inside a function only exist inside that function. Once the function is done running, the variable disappears. An as far as the compiler is concerned, they don’t exist in other functions. So you need to do the above declaration at the top of the file, not in Start().

  2. Built in arrays are zero based. So if you do:

    var vals : int = new int[10];

…you create 10 slots that can be indexed by values 0 - 9. It is best if you sure the .Length or in the case of a generic list the .Count rather than a specific value, so your could would be:

if (activeSlot < slots.Length) {
    slots[activeSlot] = log;
 } 

Note with a built-in array, there is no ‘Add’ function. You would do something like this to add a item to your array:

if (activeSlot < 25) {
    slots[activeSlot] = slot;
    activeSlot++;
 ]

There is an Add function in a generic List.


Note in a reread, I cannot decide if a generic list or a built-in array is better. You’ll have to evaluate and make the choice.