iteration through objects - how can I step through numerically named variables? (or nested / jagged 2D arrays?)

hi folks!

how could you iterate through a set of objects with almost the same name, like

var theTextpair_1 = ["Foo", "Bar"];
var theTextpair_2 = ["Foo", "Bar"];
var theTextpair_3 = ["Foo", "Bar"];

for(i=1; i<=3; i++)
{
  for(j=0; j<=1; j++)
  {
    print("theTextpair_"+i[j]);
  }
}

thanx!

It looks as though you're looking for something which resembles a 2D array.

There are two methods of implementing a 2D (or multi-dimensional) array in Unity. There are "real" multi-dimensional arrays, and there are "Jagged" arrays. The difference is this:

With a "real" 2D array, your array has a fixed "width" and "height" (although they are not called width & height). You can refer to a location in your 2d array like this: myArray[x,y].

In contrast, "Jagged" arrays aren't real 2D arrays, because they are created by using nested one-dimensional arrays. In this respect, what you essential have is a one-dimensional outer array which might represent your 'rows', and each item contained in this outer array is actually an inner array which represents the cells in that row. To refer to a location in a jagged array, you would typically use something like this: myArray[y][x].

Converting your script above to use a jagged array, would look something like this:

var textPair1 = ["Foo", "Bar"];
var textPair2 = ["Foo", "Bar"];
var textPair3 = ["Foo", "Bar"];

// create an array of arrays (a.k.a. a jagged array)
var textPairs = [ textPair1, textPair2, textPair3 ];

for(int pairNum=0; pairNum < textpairs.Length; pairNum++)
{
  var textPair = textPairs[pairNum];
  for(int itemNum=0; itemNum < textPair.Length; itemNum++)
  {
    print("the text pair "+pairNum+","+itemNum+" = "+ textPair[itemNum]);
  }
}

Due to a quirk of Unity's Javascript, you can't define a true 2D array in a JS script (only in Unity's C#), however you can work with them. Read more about that here.

However, Your question throws up a few interesting points.

  1. Array indices in Unity are zero-based. So the first item is item 0, the second item is item 1. Hence the changes to the "for" loops above. They start at zero, and then continue while the index is less than the array length. The last item in an array containing 10 items is thatArray[9].

  2. If you're actually working with sets of pairs, you don't really need to iterate over the pairs, you could just access them using

    print ("the text pair is: " + textPair[0] + ", "+ textPair[1]);
    
    
  3. There are other types of collections which are even better suited to storing pairs of items, if those pairs represent key-value pairs. The most commonly used are the HashTable and the Generic Dictionary (the latter is c# only).