Thursday, January 29, 2009

Dynamic buttons in Flash using ActionScript 2.0

I am often needing Flash to create dynamic buttons from an Array (or external TXT (text) document). Here's how I do it:

1. Make your button an actual MovieClip on the stage however you want them all to look/work. Create a dynamic text field (center justified - or whatever) within the button with the instance property of "text_txt" for this example. (You can name it whatever you want, but you'll need to change some of the code below).

2. In the library find your MovieClip. Open the Symbol properties dialog.

3. Select the "export of actionscript" check box. Identifier "myButton"... again, for this example only. Click OK.

4. Now return to the stage and in frame one of a layer, I've named my top-most layer "actions". Copy and paste the following:

for(i=0; i
target = this.attachMovie("myButton", "myButton"+i, i, {_x:10, _y:30*i} );
target.text_txt.text = nav[i];
target.myLink = url[i];
trace(myLink);
target.nr = i;
target.onPress = function(){
//getURL(this.myLink);
trace("Hi, I'm "+this._name+" and my number is "+this.nr+". The link is: " + this.myLink);
}
}

With some extra work we can make this a horizontal menu, getting the width of each text box and moving the rest.... I'll post that another time.

5. I created an Array that I want to use for the labels of my buttons. Eventually I will pull these labels from a database table, but for now, paste this info above the previous code.

var nav:Array = Array();

nav[0] = "nav 1";
nav[1] = "nav 2;
nav[2] = "nav 3";
nav[3] = "nav 4";
nav[4] = "nav 5";
nav[5] = "nav 6";
nav[6] = "nav 7";

6. Now we need these links to do something, right? So let's create an Array for our URLs. Paste this array just below the previous but before the button code "for" stuff.

var url:Array = Array();

url[0] = "http://www.adobe.com";
url[1] = "my link 1";
url[2] = "my link 2";
url[3] = "my link 3";
url[4] = "my link 4";
url[5] = "my link 5";
url[6] = "my link 6";


6. Ta da! That's all that is to it.

7. Publish your file.

No comments: