7.2. Targeting Movie Clips with Dynamic Names

Problem

You want to target a movie clip in which the clip’s name is generated dynamically.

Solution

Use array-access notation (square brackets) and string concatenation (the + operator).

Discussion

If you know a movie clip’s name, you can target it using standard dot notation:

// Target a movie clip named myMovieClipA that is within a clip named holderClip that
// is, in turn, within _root.
_root.holderClip.myMovieClipA._x = 25;

However, the situation is a little different when the movie clip’s name (or any part of the path) is not explicitly known. For example, if you have the movie clip’s name stored in a variable, you may make the common mistake of trying to use the variable name within the target path:

// This will not work! It will look for a movie clip named "myVar" instead of a movie
// clip with the same name as the value of myVar.
_root.holderClip.myVar._x = 25;    // Wrong!

Instead, you should use array-access notation. All objects, including movie clips, can be treated as associative arrays. This means that you can access any element of a movie clip—even a nested movie clip—using the array-access operator ([]). Note that while standard dot notation expects a movie clip reference, array-access notation expects a string or a variable that contains a string value:

// This works! It evaluates myVar through the use of array-access notation. It
// targets the clip within holderClip that has the same name as the value of myVar. _root.holderClip[myVar]._x ...

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.