Actionscript to Reference Dynamically created instances Flash Movie Clip | Array notation | Tutorial

    Overview:

    Often I’ve had some dynamically created movieclip and then wanted to reference it in my code. This is hard to do if it is named dynamically as well, such as with an incrementing variable. If you use one (or more) variable to name an instance in run time, you can’t always know what it will be called.
    There are two ways (that I know of) to reference these clips, one is the array operator [] and the other is using the eval() function is as2 (but I’ve noticed that as3 has removed the eval function, so I’d recommend getting used to array notation).

    Steps:

    1. Create the object dynamically (or with a variable) (_root.myClip.duplicateMovieClip (“myClip”+i, i);)
    2. Reference it with either array notation or with eval. (thisOne = _root["myClip"+i];) or (eval(“myClip” + i))

    Example:

    Get Adobe Flash player

    I create some movie clips dynamically using a for loop and name them all incrementally with a variable (myClip+i). But then i want to refer to some of them later, specifically. I don’t know what they are named though. They are all myClip1 myClip2 myClip3 and so on. I can use array notation to reference these (or eval). I’ve found it’s easiest to create a reference to the name once and then use it to refer to the clip I want. I imagined a scenario that when you click a mc you would want a different one to be moved. So clicking myClip3 moves myClip4 and so on. I’ve made it wrap so that 5 moves 1… They change the _y property of the next to match the one that’s clicked. Clicking the refresh button will loop through all the clips and (this time using eval) randomize the y coordinate.

    Actionscript:

    var myLimit = 5;
    //myClip._visible = false;

    for(var i=1; i<=myLimit; i++) {
    _root.myClip.duplicateMovieClip ("myClip"+i, i);

    thisOne = _root["myClip"+i];
    thisOne._y = Math.random() * Stage.height;
    thisOne._x = Stage.width/(myLimit+1) * i ;
    thisOne.id = i;
    thisOne.idDisplay.text = i;

    thisOne.onRelease = function() {
    nextOne = (this.id == myLimit) ? _root["myClip"+1]: _root["myClip"+(this.id+1)];
    nextOne._y = this._y;
    }
    }

    myClip.onRelease = function() {
    for (var i=1; i<=myLimit; i++) {
    eval("myClip" + i)._y = Math.random() * Stage.height;
    }
    }

    Download:

    Source fla file: download

    Reference:

    Nuno Mira shows a good example:

    this.createEmptyMovieClip("outer_mc", 1); // create a mc called outer_mc
    outer_mc.createEmptyMovieClip("inner_mc", 1); // create a mc called inner_mc inside outer_mc
    // 3 different ways of targeting inner_mc
    trace(outer_mc.inner_mc);
    trace(outer_mc["inner_mc"]);
    trace(this["outer_mc"]["inner_mc"]);
    // all output _level0.outer_mc.inner_mc

    TheCanadian@Kirupa states it nicely:
    The Problem
    How can I reference objects using a variable? This is commonly a problem with dynamically created buttons:

    ActionScript Code:
    for(i = 0; i < 3; i++) { button+i.someProp = "Hello World!"; //error }

    The Answer
    This is probably the question that gets asked the most. Referencing an object with a variable is done using something called associative array referencing or array notation. The fundamental concept behind this is that:

    ActionScript Code:
    myObject.prop = "value"; //and myObject["prop"] = "value";

    Are the same thing. Associative array referencing follows the pattern of scope["prop"] where scope is the object which contains the property and prop is the name of the property you wish to reference. Save appearance, array notation works in exactly the same way as dot notation.

    Going back to the original, problematic, example, the correct code would look like this:

    ActionScript Code:
    for(i = 0; i < 3; i++) { this["button"+i].someProp = "Hello World!"; }

    The button string is concatenated (joined) with the i variable, forming a new reference with each iteration of the loop. First button0, then button1, et cetera.

    That’s the quick, but some of you may think that that’s the same notation that is used with instances of the Array class. While that is true, the converse is actually more correct: Array instances use that notation.

    Arrays are exactly the same as generic Objects, the only difference is that they have a collection of methods to deal with their properties. And because they require a need for organization, they typically only use numerical properties. Given the array myArray = ["a", "b", "c"], you could theoretically reference the indices using myArray.0, myArray.1 and myArray.2. The reason that we must use array notation is because the compiler doesn’t allow the reference of numerical properties with dot notation.

    This entry was posted in tutorial and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    One Comment

    1. Boon
      Posted August 18, 2008 at 9:43 pm | Permalink

      It’s probably misleading to say that arrays are exactly the same as generic objects, even though from the perspective of syntax it looks like so. One clear difference is that indexed array maintains a length property, but generic objects do not maintain this information.

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...