7.10. Discovering Nested Movie Clips
Problem
You want to use ActionScript to retrieve an array of movie clip instances nested within a specific movie clip.
Solution
Use a for . . . in
statement
to loop through all the contents of
the movie clip, and if the content is an instance of the
MovieClip
class (as indicated by the
instanceof
operator), add it to an array of the
nested movie clips.
Discussion
Movie clips can be nested within other movie clips. A nested clip
instance is stored as a property of its parent clip. Since movie clip
instances are objects, you can access all the nested movie clips
using a for . . . in
statement. However, a basic
for . . . in
statement lists other properties in
addition to nested movie clips. This example displays not only movie
clips nested in _root
, but also any timeline
variables, functions, and the built-in $version
variable:
for (var item in _root) { trace(item + ": " + _root[item]); }
To separate nested movie clips from the rest of a
clip’s contents, you can use the
instanceof
operator to check if an item is an
instance of the MovieClip
class, as follows:
// The if
statement disregards everything but movie clips.
for (var item in _root) {
if (_root[item] instanceof MovieClip) {
trace(item + ": " + _root[item]);
}
}
You can also write a simple custom method for the
MovieClip
class that returns an array of nested
movie clips:
MovieClip.prototype.getMovieClips = function ( ) { // Define the array to contain the movie clip references. var mcs = new Array( ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.