Flash AS3 Tutorial: How to Create 2D or 3D Dynamic, Multi-Dimensional Arrays
So creating a dynamic 2-dimensional array in flash isn’t as easy as you’d think. Instead of being able to just assign variables into a specific row/column position you have to initialize an array of arrays. Below are code snippets to help you init 2D and 3D arrays.
Creating a 2D Array
var multiDimensionalArray:Array = new Array(); var boolArray:Array; var MAX_ROWS = 5; var MAX_COLS = 5; //initalize the arrays for (var row = 0; row <= MAX_ROWS; row++) { boolArray = new Array(); for (var col = 0; col <= MAX_COLS; col++) boolArray.push(false); } multiDimensionalArray.push(boolArray); } //now we can set the values of the array as usual for (var row = 0; row <= MAX_ROWS; row++) { for (var col = 0; col <= MAX_COLS; col++) boolArray[row][col] = true; trace('boolArray ' + row + ',' + col + ' = ' + boolArray[row][col]); } }
Creating a 3D Array
var multiDimensionalArray:Array = new Array(); var boolArray:Array; var anotherBoolArray:Array; var MAX_X = 5; var MAX_Y = 5; var MAX_Z = 5; //initalize the arrays for (var x = 0; x <= MAX_X; x++) { boolArray = new Array(); for (var y = 0; y <= MAX_Y; y++) { anotherBoolArray = new Array(); for (var z = 0; z <= MAX_Z; z++) anotherBoolArray.push(false); boolArray.push(anotherBoolArray); } multiDimensionalArray.push(boolArray); } //now we can set the values of the array as usual for (var x = 0; x <= MAX_X; x++) { for (var y = 0; y <= MAX_Y; y++) { for (var z = 0; z <= MAX_Z; z++) { boolArray[x][y][z] = true; trace('boolArray ' + x + ',' + y + ',' + z + ' = ' + boolArray[x][y][z]); } } }
Hey, thanks so much for your explanations, it’s very well done.
I’m trying right now to create a 2D array but with objects. Say I have f.e. 3 gameLevels and each gameLevel has 3 objects.
I tried to create a temp name of object type, that will have “level” + the i of the for (all this inside a for , of course). Then I push the array with that name. It works, but the levels are not stored as objects, but as string I believe.
What you think this can be?
Thanks so much for your guidance !! And again, well job !!
You can store objects in the array too, you just need to make sure you’re creating an instance of the class dynamically and then use that variable to create the level object. You’ll also need to import flash.utils.getDefinitionByName;
var level:Class = getDefinitionByName(“level” + i) as Class;
levels_array.push(new level);
I got it right !! Thanks so much Jade for your help !!
Very helpfull!
Thanx a lot!
thanks !Very Helpful, I was almost there by the time I saw your post but it reassured me that I was not over complicating things…