Accessing contents of an array

Hey there,

Still trying to get to grips with the basic methods of scripting in Unity. I asked what I guess might be seen as a pretty dumb question yesterday regarding referencing gameobjects and I’m back today with one regarding Arrays. Please believe me when I say that I do spent a long time (often hours) trying to work it out for myself, or trying to research the answer before posting on here (And I have read the Basic Scripting Guide) :wink:

Problem I’ve got is that I have about 5 arrays, called array1, array2, array3 etc. Let’s say I had a function that would access one of these arrays and pull the 2nd value from it with a parameter (i) telling the function which array it should be looking at…

function getVal(i:int){

Debug.Log(whatgoeshere?[1])
}

I come from an actionscript background where I could do something like…

trace (this["array"+i][1]);

…but if I try a similar thing in Unity like…

Debug.Log(gameObject.GetComponent["array"+i][1]);

…I get various errors, depending on how I do it.

Thanks in advance…

public var goArray : GameObject[]; //an array of gameobjects, to be populated in the editor

function Start(){
    Debug.Log(goArray[1].name); //print the name of the second GameObject in the array
}

Sorry, thanks for taking the time to reply, but I don’t really understand your answer in terms of it helping me. Let’s say that the array was called ‘goArray1’ and I wanted to access it by means of “goArray” + i (with i equalling 1), how would I go about that? If I try methods like those described in my original post I get back something like ‘Type ‘int’ does not support slicing’ etc. I appreciate you posting though :slight_smile:

Well an array is just a container variable, not a Monobehavior, so GetComponent wouldn’t do you any good. I think I see what you’re saying now though, you want to have a bunch of arrays, whose names’ have a number at the end, and you want to iterate through them by editing their names’ like a string and appending an int on the end? You can’t really manipulate variable names like that in Unity. You’d probably have to make an array of arrays.

One way to do it would be to use a single, multi-dimensional array instead of multiple, single-dimensional arrays. So, instead of having this:

array1[0]
array1[1]
array1[2]
array2[0]
array2[1]
array2[2]

You’d have this:

array[0,0]
array[0,1]
array[0,2]
array[1,0]
array[1,1]
array[1,2]

Then, you could easily reference any particular location via a row and column parameter.

Thanks to you both. I did consider the array of arrays, but before I threw myself into it, I wanted to make sure it wasn’t a case of me just getting my syntax messed up and the old Actionscript method was actually possible in Unity. Once again I’ve learned something :slight_smile: Many thanks