Monday, 21 June 2010

Number of objects on stage in AS3

If you ever want to tell how many objects there are on the stage, you can use the following code below. This code is useful if you are adding multiple movie clips dynamically on the stage and want to quickly see if the correct numbers have been added.

trace(this.numChildren, “number of objects on the stage”);

Sometimes it is hard to determine a movie clip depth/index on the stage. You can find out the index of an objects instance by using getChildAt() method, so the code below will give you the instance name of the object at the index 1.

trace(this.getChildAt(1), “the depth at index 1”); 

The getChildIndex() method from code below is like the opposite of the getChildAt() method. You give the objects instance name and the index gets returned.

trace(this.getChildIndex(yourInstanceName), “the depth of  yourInstanceName”);

If you have more than one object on the stage and you want to get the instance name of the object. You can use the numChildren property to get the number of objects on the stage, and use the getChildAt() method inside a For loop to get the instances name like below.

for(var i:uint = 0; i < numChildren; i++){
trace(getChildAt(i).name)
}

This also works if you have multiple objects inside a movie clip, you would do this.

for(var i:uint = 0; i < nameOfMovieClip.numChildren; i++){
trace(nameOfMovieClip.getChildAt(i).name)
}

One of the main reasons for using the code above is saving time and speed. If you have twenty movie clips on the stage and you want instance names in an array, you can use the code below instead of typing out all the names individually into an array.

var myArray:Array = new Array();
for(var i:uint = 0; i < numChildren; i++){
myArray.push(getChildAt(i).name)
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP