Assigning dynamic/unique variable names in a for loop in AS3

Assigning dynamic variable names to objects created in a for loop in AS3.

You have to get very creative to search these questions on google because words like “for” and “loop” are so utterly common.

If you have a loop in AS3 creating multiple variables but need them to have unique names (for later modification) you need to create something like an array to store the references to the variables.

For example, anything you create in a for loop is a temporary reference. It disappears after the loop is complete, and whatever objects were created stick around in the displayObject.

In my situation I had a loop creating my navigation elements, but needed to position each X value separately.

Here is the method I used to keep the references to these variables:

private var mcArray:Array = new Array();  // array that holds references
private function myfunction():void{
	for (var i:int=0; i<2; i++) { 
		var movieClip:MovieClip = new MovieClip(); // the temporary variable
		addChild(movieClip);
		mcArray[i] = movieClip; // store reference to temporary variable in array
	}
}

Now, to use those references:

mcArray[0].method_here;
// or
// --
for (var i:int=0; i<2; i++) {
	mcArray[i].foo = bar;
}

To be absolutely clear, the above example creates two MovieClips according to the loop (while i < 2), and places each MovieClip in the mcArray array at index i (which we have defined as the integer counting the loop).

Now if I wanted to access those individual MovieClips I could use the mcArray to do so.

mcArray[0].graphics.beginFill(0x555555,1);
mcArray[0].graphics.drawRect(0,0,900,300);
mcArray[0].graphics.endFill();</code>

I could also loop through the array to apply an animation to each item. The possibilities are endless when you use this basic concept!

Generate 1000 triangles. Animate each one to a random color and rotation.

40 Comments

  1. Fin says:

    Thanks so much for this. I’ve been trying to do this all night. I couldn’t work out how to refer back to the movieclips I’d made and putting them into an array was perfect! 😀

  2. ryu619 says:

    Very helpful. Thanks.

  3. Jerome says:

    all the code in one block would be nice.
    With parts of code like this, i could not recreate this script in flash cs3.

  4. Vikky says:

    WOW YOU ARE THE MAN…
    AT LAST I CAN SLEEP PEACEFULLY TONIGHT 🙂
    THANK YOU VERY MUCH…

    CHEEEEEEEEEEEEEEEEEERS

  5. Rob says:

    Thank you, that helps a lot!

  6. Ronald says:

    You saved my day.

  7. jason says:

    Why do you put addChild there? I don’t know ActionScript but I would have figured to do it like this:

    mcArray[i] = movieClip;
    addChild(mcArray[i]);

    I would have thought to do it like this:

  8. jef says:

    thank you! I was going insane trying to figure this out coming from AS2. It forms the basis for everything so thank you.

  9. tom says:

    This seems also a possible way to be able to set to null objects removed from the display list created within loops? – as in:
    removeChild(mcArray[0]);
    mcArray[0]=null;

    or is there a simpler way?

  10. saintist says:

    veri nice, i find this, thank, you save my time

  11. saintist says:

    veri nice, i find this, thank, you save my work time

  12. pablo says:

    Thank you so much. I couldn´t figure out how to do it.

  13. Marcus says:

    I have following path to some movieclips.
    this.vote1.v0.addEventListener(MouseEvent.CLICK, SaveVote);
    this.vote1.v1.addEventListener(MouseEvent.CLICK, SaveVote);
    this.vote1.v2.addEventListener(MouseEvent.CLICK, SaveVote);
    this.vote1.v3.addEventListener(MouseEvent.CLICK, SaveVote);
    this.vote1.v4.addEventListener(MouseEvent.CLICK, SaveVote);

    Who do i make this with a for loop?

  14. Xerks says:

    Thanks for the great tip, I found it very useful. How could I modify this so I can add a movieclip to a 2-d array? I’m trying to create a grid of tile movieclips and I want to be able to add another clip to coordinates within the grid. I’d imagine it would end with something like:
    mcArray[0][0].METHOD_HERE;

    Any help would be appreciated.

    1. Yuji says:

      You want to associate one MC to an array coordinate?

      I’m pretty rusty here, but how about..


      //define 5x5 2d array
      2dArray = new Array();
      2dWidth = 5;
      2dHeight = 5;

      for (var i:int=0; i<2dHeight.length; i++) {
      2dArray[i] = new Array();
      for (var ii:int=0; i<2dWidth.length; ii++) {
      2dArray[i][ii] = new Array();
      2dArray[i][ii]['mc'] = myMovieClip;
      }
      }

      //alter 0,0 coordinate
      2dArray[0][0]['href'] = 'store other arbitrary data on grid';
      2dArray[0][0]['mc'] = myMC;

      //access row 2, col 4 MC
      2dArray[2][4]['mc'].do_something;

  15. Dan says:

    THANK YOU! THANK YOU! haha. u saved the day.

  16. oscar pardo says:

    Muchas gracias Amigo!

  17. Ben says:

    this is excellent, saved me going round in circles for sure, you are a genius!

  18. Rowland says:

    Nice one, thanks bud

  19. badcoder says:

    Thx u very much..

    it’s hopeful

  20. Lazzaro says:

    grazie mille! thank you from Italy

  21. Santosh says:

    Thanks…! u saved my many hrs. thank u very much..

  22. Daniel Shumway says:

    Amazing. Dynamic variable names were one of my favorite things about actionscript 2.0 and they seem much harder to do now. This is so useful.

  23. Mahrukh says:

    Wow this is so useful, I’ve been trying to figure this out for days, you’ve saved me life. Really.
    Thank you 🙂

  24. Darque says:

    Thank you very much for sharing this code. I have a question tho. How would I use this for something like the SoundChannel class?

    If I want to play each channel, I would end up doing something like this:

    channelArray[i] = soundArray[i].play;

    Which might actually assign a Sound object to channelArray.

  25. Florent says:

    Thank you very much for the tip !

    If I hadn’t visited this page, I would probably never ended my project !

  26. Sang says:

    Good day! I just found your webpage: Assigning dynamic/unique
    variable names in a for loop in AS3 | Useful Stuff.
    when I was browsing reddit.com. It looks as though someone appreciated your blog so much they decided to bookmark it.
    I’ll unquestionably be returning here more often.

  27. Rayford says:

    One must practice the comic scripts beforehand at home.
    Think of this as a way to document your improvements over time, and eventually it will be a very effective PR
    tool. He hosted Comedy Central’s’The Man Show’ as well as
    the ubiquitous pseudo-porn for the sexually crippled, ‘Girls Gone Wild’, both solely and
    shamelessly for financial gain.

  28. Hi there to all, the contents existing at this web site are actually awesome for people knowledge,
    well, keep up the nice work fellows.

  29. Tammie says:

    This might be the best blog for everyone who wishes to
    be familiar with this topic. You already know much its practically not easy to
    argue along. Outstanding stuff, just great!

  30. Hello colleagues, how is all, and what you wish for to say concerning this post, in my view its actually
    remarkable in favor of me.

  31. Of download rust course the sports world simply couldn’t imagine a year, Black Ops 2Developer:
    TreyarchRelease Date: Nov. But, should access be limited in respect to their
    children to care for animals when they aim at your face
    or perhaps U. Video games have become very hard to find these cheat codes throughout
    the video game. This is to advertise effectively in a week after its release and flop financially – these
    games.

  32. If the eighty three percent of all types of videogames
    are their best to dayz download make a list of the quoted official.
    This only causes the child thinks less of an instrument stimulating enough?
    While there are a great way to copy and backup your Playstation 3 games.

  33. I don’t even know the way I finished up here, however I
    believed this post was once great. I don’t recognise who you might be but definitely you are going to a well-known blogger when you aren’t already.
    Cheers!

  34. Greetings! I’ve been reading your site for some time now and finally got the courage
    to go ahead and give you a shout out from Austin Tx!
    Just wanted to tell you keep up the excellent work!

  35. Rebecca says:

    We stumbled over here different web address and thought I might check things out.
    I like what I see so now i am following you. Look forward to going over your web page repeatedly.

  36. Samira says:

    Hello to all, it’s genuinely a good for me to pay
    a quick visit this web site, it contains important Information.

  37. Miloš from Prague says:

    Very helpfully for me!! Thanks a lot! Simple and strong!

  38. redmund says:

    your are a genious man, direct to the point, very very clear to me now. thumbs up!

Leave a reply to oscar pardo Cancel reply