Tuesday, 29 June 2010

Add dynamic instances to an array

Let’s say you have the following scenario, you have multiple movie clips in the library that you want to add dynamically into an array. There are two ways I discovered that this can be achieved. The first method involves writing out all the class names in an array like below. The code below assumes you have three movie clips in the library with class names: shape1, shape2, and shape3.

var shapeArray:Array = new Array (new Shape1(), new Shape2(), new Shape3()); 

This method works fine, but what if you have more than five movie clips in the library. For example, you have twenty movie clips or more that you wish to add into an array. You can use the same method as above although you would need to write out a lot of code. To make your life easier you can use the getDefinitionByName() method to get the name references for all the movie clips in the library. The code assumes you have ten movie clips in the library.

var numOfShape:uint = 10;
var shapeArray:Array = new Array();

for(var i:uint = 1; i < numOfShape+1; i++){
    var ShapeClass:Class= getDefinitionByName ("Shape"+i) as Class;
    shapeArray.push(new ShapeClass())

The code works by getting the class names of the Movie clip using the getDefinitionByName() method and pushing the values into an array.


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP