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 namedmyMovieClipAthat is within a clip namedholderClipthat // 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 thevalueofmyVar. _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 evaluatesmyVarthrough the use of array-access notation. It // targets the clip withinholderClipthat has the same name as the value ofmyVar. _root.holderClip[myVar]._x ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access