7.11. Getting Unique Depths

Problem

You want to easily ensure that you always get a unique depth when creating a new movie clip using createEmptyMovieClip( ), attachMovie( ), or duplicateMovieClip( ).

Solution

Create and use a custom MovieClip.getNewDepth( ) method.

Discussion

Only one movie clip can exist at each depth within a parent clip, so if you specify an existing depth when using createEmptyMovieClip( ), attachMovie( ), or duplicateMovieClip( ), the movie clip already on that depth is overwritten. Unless you want to overwrite an existing movie clip, you must always use a unique depth when using these methods.

ActionScript does not provide native support for generating a unique movie clip depth. You must keep track of all the used depths yourself. When you add only a few movie clips programmatically, this does not pose a problem; however, if you programmatically generate many movie clips, it becomes difficult to track which depths are already used. Fortunately, you can solve this problem easily with a few lines of code.

You can add a getNewDepth( ) method to the MovieClip class so that every movie clip inherits it, as shown in the following code block. The process is not complex. If the movie clip does not yet have a custom currentDepth property defined, we define it and initialize it to the value of 1. The value 1 is used because that is the first depth you want to assign to any programmatically generated nested movie clip in most cases. Once the method ensures that the

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.