Utilizing the Power of Arrays in Adobe Flash
Posted by Anthony in Flash, Tutorials tagged actionscript 3, arrays, Flash
Each time I program a project in Adobe Flash using ActionScript, I try to keep the code as concise as possible—partly because it helps in processing the code, and partly because I’m a nut for clean code that’s easy to update on the fly with minimal effort. In ActionScript 3.0, I am continually finding myself coming up with new ways to clean up my code and keep it as lean as possible. One way I do this is through the use of Arrays.
Now Arrays are nothing new to any programmer out there, but I find that in ActionScript 3.0, I’m using them much more so than I ever did in ActionScript 2.0. The main reason for this is that I like to use the same set of functions for button actions over a range of similar buttons. Since ActionScript 3.0 requires you to pass a function into each listener event for every button, I like to use Arrays to sort my buttons and accompanying objects, and thereby creating the chance to use the same function for all buttons.
The sample Flash movie below shows this in action. I created a very simple 4-section flipbook, and have used the same function for all Mouse Click events.
Here’s the code used for this movie. Note how concise the code is, thanks to the use of my two main arrays.
/* — Begin Code — */
var links:Array = [link0_mc, link1_mc, link2_mc, link3_mc];
var pages:Array = [page0_mc, page1_mc, page2_mc, page3_mc];
function setLinks():void {
for (var i:int=0; i<links.length; i++) {
links[i].id = i;
links[i].buttonMode = true;
links[i].addEventListener(MouseEvent.CLICK, linkClick);
}
}
function linkClick(e:MouseEvent):void {
hideAllPages();
showPage(e.currentTarget.id);
}
function hideAllPages():void {
for (var i:int=0; i<pages.length; i++) {
pages[i].visible = false;
}
}
function showPage(pageNum:Number):void {
pages[pageNum].visible = true;
}
hideAllPages();
showPage(0);
setLinks();
/* — End Code — */
In this Flash movie, the links and pages are named with the same numerical value (i.e. link0_mc corresponds to page0_mc). They also share the same place in their respective arrays, creating the ability to utilize loops in the linkClick and hideAllPages functions.
Of course this is just a simple example, but with a little extra effort, the same concept can easily be used for more complex applications. Happy coding!

Facebook
LinkedIn
Twitter
Pretty good post. I just came across your site and wanted to say
that I have really enjoyed reading your posts. Anyway
I’ll be subscribing to your feed and I hope you post again soon!