FORUMS: list search recent posts

dynamically assign variable to MovieClip

COW Forums : Adobe Flash

<< PREVIOUS   •   FAQ   •   VIEW ALL   •   PRINT   •   NEXT >>
Greg DiGenti
dynamically assign variable to MovieClip
on May 2, 2011 at 4:27:32 pm

I have a series of MovieClip "buttons" (called button_1, button_2, button_3, etc) nested in a MovieClip called allButtons. I'm trying to assign a number (which I'm calling theTrigger) to each of them so that when they're pressed I can call that number.

Just so you know nothing's misnamed, this code works, but it's not dynamic:
allButtons.button_1.theTrigger = 1;
trace(allButtons.button_1.theTrigger); //Returns 1

And this is the code I'm attempting to make work in a for loop, but doesn't:

var buttonCount:int = 4;
for (var i:int=1; i<=buttonCount; i++) {
this["allButtons.button_" + i].theTrigger = i;
trace(this["allButtons.button_" + i].theTrigger);

That last code just returns this error:
TypeError: Error #1010: A term is undefined and has no properties.

Return to posts index

demetri tashie
Re: dynamically assign variable to MovieClip
on May 2, 2011 at 5:24:00 pm

you would be best served by utilising an array.

if you put the names of the buttons in an array, you can access it by the index number of the array. just remembr that the first index of an array is 0, not 1.

look at this code, and hopefully it will makes sense to you.
var buttonArray:Array = [ allButtons.button_1, allButtons.button_2, allButtons.button_3];

var buttonCount:uint = buttonArray.length;

for (var i:uint=0; i< buttonCount; i++) {
buttonArray[i].addEventListener(MouseEvent.CLICK, outputNumber);
buttonArray[i].theTrigger = [i];

function outputNumber(e:MouseEvent):void {

you'll see that the 'for loop' generates both your 'theTrigger' number, as well as the event listener for each button.

If you just can't deal with your first button's number being 0, change this line to:
buttonArray[i].theTrigger = [i+1];

hope that helps

Return to posts index

Greg DiGenti
Re: dynamically assign variable to MovieClip
on May 2, 2011 at 5:32:24 pm

Wow, that's genius. And you added the MouseEvent listener to the loop as well, which slims my code down even more. Thanks!

Return to posts index

<< PREVIOUS   •   VIEW ALL   •   PRINT   •   NEXT >>
© 2018 All Rights Reserved