Accessing Movie Clip Properties as an Array


Remember in Chapter 4, "Creating Instances Dynamically: The Button Menu," when we used the eval function? eval was used to create a dynamic reference at run-time. That explanation mentioned that there was a more elegant way to create a dynamic reference at run-time. The array notation allows us this new solution.

First, you must understand that all members of an object can be referred to using array notation. This will seem strange at first, but bear with me. Consider the following example, which shows two different ways to refer to some newly created empty movie clips:

 for(i=0; i<5; ++i)     createEmptyMovieClip("empty"+i, 1); //old way of referring to them for(i=0; i<5; ++i)     eval("empty"+i)._x += i*100; //new way of referring to them for(i=0; i<5; ++i)     this["empty"+i]._y += i*50; 

In the first for loop, five new clips are created. In the second for loop, their _x values are staggered across the stage using eval to create the dynamic reference. In the third and final loop, their _y values are staggered. Notice the way the array notation refers to the clip instead of eval . If you test this script, you won't actually see anything because we're creating empty movie clips.

Figure 5.21 shows that eval and array access work the same way. What is returned by the trace commands are the paths to the movie clips being referenced.

click to expand
Figure 5.21: The eval function gives an absolute path , whereas array notation gives a relative one.
 for(i=0; i<5; ++i)     createEmptyMovieClip("empty"+i, i); for(i=0; i<5; ++i)     trace(eval("empty"+i)); for(i=0; i<5; ++i)     trace(this["empty"+i]); 

As you can see, this script creates five empty clips and then traces references to all of them, first with eval and then with array notation. Notice that the array that is being accessed is this. You can access the contents of any timeline as an array. Unlike in previous examples, you would not use an implied this . If you do, Flash returns an error when the file is published.




Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net