A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: Call and run a random function from an array of functions?

  1. #1
    Junior Member
    Join Date
    Oct 2008
    Posts
    21

    Call and run a random function from an array of functions?

    So I'm attempting to call a random item from an array which is all fine and dandy, but I'm attempting to fill the array with functions, and therein lies my problem.

    Here is my code, it's just a test file I made to keep it simple while I learn how to do it:
    Code:
    var functionArray:Array = new Array('a', 'b', 'c');
    
    function a():void
    {
    	trace("a!");
    }
    function b():void
    {
    	trace("b!");
    }
    function c():void
    {
    	trace("c!");
    }
    
    stage.addEventListener(MouseEvent.CLICK, onClick);
    
    function onClick(event:MouseEvent):void
    {
    	var randomNum:int = Math.floor((Math.random() * functionArray.length));
    	(functionArray[randomNum])();
    }
    The final product would involve me clicking the stage and getting a random letter yelled back at me via trace. This is not exactly what I need for my game but this is the basic structure that I can then build upon later.

    Any suggestions?

  2. #2
    Member
    Join Date
    Jul 2005
    Location
    Brisbane, Australia
    Posts
    66
    You can reference functions by their name, so

    PHP Code:
    var functionArray:Array = new Array(this.athis.bthis.c); 

  3. #3
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    You don't even need the 'this'. The original problem was that you were putting Strings in your array instead of Functions.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center