Using Function: The Beginner's Nightmare - More on reusability: practical example
(Page 4 of 5 )
To further encourage you not to give up on your way in becoming advanced actionscript programmer, here are some practical situations that should give you an idea of what benefits you could count on when you decide to move on from gotoAndStop() to some serious work.
Example:
Let’s say that you’ve built a Flash application that uses sound effects which will be repeated multiple times through your code. This is fine and it probably works fine. Then, your client requests an option to be able to switch sounds and sound effects on and off. That gets you lots of trouble and tons of additional code for every sound.
What about using a sound handling function?
Place all sounds in separate movie clips, first frame is empty and on stop(), second one is containing your sound. Set instance names to them regarding sounds they contain and then declare a function on main timeline with the parameter that will call the sound movie clip.
function makeSound(sound){
_root[sound].gotoAndPlay(2);
}
Now, instead of doing different actions with sounds you could simply invoke this function with the sound name as a parameter from wherever in your entire application:
_root.makeSound("bird");
In the same situation when you need to control overall sound appearance in your movie, you could just alter your function with a condition that checks if sound is allowed or not.
First, visualize your sound on/off in a toggle button or any other aspect that could give user interaction ability. Set it up so it changes the variable on the main timeline, which would be used as a kind of flag. Initial setup is true which means the sound is on.
allowSounds= true
Using your option you must be able to toggle this variable to true or false. Then just alter your makeSound function:
function makeSound(sound){
if (_root.allowSounds==true){
_root[sound].gotoAndPlay(2);
}
}
It is obvious that all sounds will be played only when your flag is set to true, otherwise, function will be called without doing any actions.
Can you imagine what numerous solutions can you do with this basic approach? Could you see more solutions to your everyday beginners actionscripting? Once you feel the power of code optimization, you will be able to do increasingly satisfying high-end solutions. However, not to forget, you better start with functions first.
Next: Conclusion >>
More Flash Articles
More By Aleksandar Horvat