Calling Named Functions Dynamically in Flash 5

Posted to the FN-FORUM mailing list:

“I have just had to dust off Flash 5 after a year or so and have hit a problem. I have one group of four functions which are different animation effects, the other group of four sets different colours on these effect functions. Now, what I want to do is return a random function once an event occurs…how?!?!!? I have been trying for hours and not even google or the flash coders wiki seem to have any pointers.”

Flash 5 doesn’t support the later Function class that Flash 6+ does, so how do you call a named function dynamically without a bunch of if(...) statements?

Well, you could use the special Flash asfunction protocol, which is for any URL that calls a Flash function, not just for links in text boxes. Here’s an example:

// id of the function to call
fn_id = Math.floor(Math.random()*4);
// set the function name
fn_name = "fn"+fn_id;
// call the function using getURL, passing null as parameter
getURL("asfunction:"+fn_name+",null");
 
// and here are the functions
function fn0() { trace("fn0 called"); }
function fn1() { trace("fn1 called"); }
function fn2() { trace("fn2 called"); }
function fn3() { trace("fn3 called"); }

Download this code: DynamicFlash5FunctionCalls.as

Tada. And this can be used for any function where the name of the function is called dynamically, and parameters can be placed where null is specified in the getURL() line.

I’m really surprised that no-one’s thought of this before…

Leave a Reply