Actionscript 3 (Flash CS6): Play a random movie clip when button pressed

The following code shows you how to play a random movie clip when a button is pressed in Flash CS6 Actionscript 3 (AS3). To do this, I started with 4 movie clips that will be called at random. So that means that there is a main timeline and 4 movie clips, each with a button in them, that are placed on the main timeline.

This code goes into the main time [CODE]

stop();

//this code makes each movie clip invisible so its not being played. I put each movie clip on the main timeline you just cannot see them until they are called
//easy1 easy2 easy3 and easy4 are instances. Be sure to give each of you movie clips an instance name.
easy1.visible = false;
easy2.visible = false;
easy3.visible = false;
easy4.visible = false;

//create an array with your instance names
var storeArray:Array = [easy1, easy2, easy3, easy4];

This is what the button does when pressed
function easyButton(pEvent:MouseEvent):void {
//random clip from array. Note that these are all variables here no instances or anything.
var myNumber = Math.floor(Math.random()*storeArray.length);
trace(“myNumber “+myNumber);
var activeCarton = storeArray[myNumber];
//now we make the movie clip that was previously playing invisible and the new one replaces it
easy1.visible = false;
easy2.visible = false;
easy3.visible = false;
easy4.visible = false;
activeCarton.visible = true;
}

[ENDCODE] Now, in the timeline with my button, I put the following code. Keep in mind my button is in my movie clip. If yours was in the main timeline you would just delete that MovieClip(root). from the code:

[CODE]

//easy1Button is the button instance name. easyButton is the function we created in the previous code.
easy1Button.addEventListener(MouseEvent.MOUSE_UP, MovieClip(root).easyButton);

[ENDCODE]

Posted in Adobe Flash and tagged , , .