Game Development Reference
In-Depth Information
At the root of all the different classes in ActionScript are basic
Objects. They are the building blocks for every other more complex
data type. They are also dynamic and therefore useful by them-
selves as lists. Every variable added to them is indexed by a string
name. Here is an example that stores a Sprite in a list by its name:
var enemyList:Object = new Object();
var enemy:Sprite = new Sprite(); = " BadGuy1 " ;
enemyList [] = enemy;
Now let
s say you had a whole batch of enemies. You could use
a for loop to add them to the list.
var enemyList:Object = new Object();
for (var i:int = 0; i < 10; i++) {
var enemy:Sprite = new Sprite(); =
enemyList [] = enemy;
Later on, if you need to perform an action on all your enemies,
you could simply run another for loop, but this time a for
in loop.
for (var i:String in enemyList) {
var enemy:Sprite = enemyList[i];
s worth noting that when you iterate through an object using a
in loop that it goes through the object in reverse order from
newest item added to oldest, so you can
t count on an object for
your items to be in a particular order. However, when order doesn
matter in your list, this is a powerful tool because you can gain
direct access to any item in the list. If you need to remove an item
from an object list, you simply use the delete command along with
the item
a string value. In the
example above, each enemy in the list is indexed by its name, and
future attempts to access this enemy can only be done if you know
its name or run through a loop to find it. Suppose when the user
clicks on an enemy, it should be destroyed and therefore be
removed from the list. Once the enemy is clicked on, you have a
reference to it through a MouseEvent. You could then remove it
from the list like the following example.
protected function enemyClicked(e:MouseEvent) {
var enemy:Sprite = as Sprite;
delete enemyList[];
s key. Items in objects are
keyed off
Search Nedrilad ::

Custom Search