In this easy lesson you will learn to use the switch/case ActionScript conditional logic. You will see that in some cases it has many advantages over the if/else conditional statement. You’ll also learn:
- How to read the Instance name of a movie clip dynamically via ActionScript,
- How to extract a specific part of a piece of text,
- How to pass a variable to a function,
- How to make Flash display text in a text field,
- What are the best practices when placing ActionScript code into your movie,
- How to choose good Instance names and more.
The simple example below shows the switch/case conditional statement at work. Try clicking every of the four icons and see what gets displayed in the text field.
Creating the movie's contents
Before starting to code this small application, you will just create a few simple movie clip symbols, give them Instance names and set up a dynamic text field.
1 Open a new Flash document.
2 Call the first layer content.
3 Draw a car on the stage — it doesn't have to be anything sophisticated, just make a simple drawing that will serve you in this lesson.
4 Select the whole drawing with the Selection tool (V) and then press F8 to convert it into a symbol. In the window that appears, select Movie clip as type, call it car and click OK.
5 Once you have created your movie clip, it will be selected by default. Go to the Property inspector panel below the scene. You will find the Instance name field on its left side. Type in car_mc and press Enter to confirm that.
It is the Instance name that makes possible to manipulate a symbol dynamically via ActionScript. The symbol's Library name (car in this case) isn't important at all in this regard, and in fact doesn't mean anything to ActionScript.
By assigning an Instance name with the suffix "_mc" to a movie clip you let Flash know that this is really a movie clip symbol and not a button, for example. You'll see later that once you begin to reference this movie clip in ActionScript code by its Instance name, Flash will offer you code options that are reserved for movie clips only, which is very efficient and saves you time.
6 Next, draw a boat, a plane and something completely different and convert each one of them into a movie clip symbol. In fact, as far as I am concerned, you can draw a triangle, a rectangle or a simple brush stroke. The important part is that you should have three more movie clips. Once you've done that, you should have a total of four movie clips on your stage. Also, their Library names aren't important in this project, so you can leave the names Symbol 2, Symbol 3 etc. if you wish.
7 Assign Instance names to the three remaining movie clips: call them boat_mc, airplane_mc and island_mc. Now these are important. I suggest that you call them like this because it will be easier for you to follow the code and explanations throughout the tutorial.
8 Select the Text tool (T). In the Property inspector, select the following options:
- Select a Dynamic Text field. You need this kind of text field to be able to manipulate it via ActionScript.
- Select a generic font family: sans, for example. Choosing this will result in Arial font being displayed on a Windows machine and Helvetica on a Mac. This, in conjunction with the Use device fonts option (see 5 below) reduces your final SWF's size because the font information doesn't have to be embedded in your SWF — it is being loaded from the user's system.
- Choose 12 as font size.
- Select black as color or any other that is easily readable in relation to your movie's background color.
- As the rendering option, select Use device fonts.
- You may turn on the border of your text field so that you can see it immediately.
9 Click and drag your mouse to create a dynamic text field on the stage.
10 Press Esc to exit the text field (the cursor automatically appears inside a text field once that you have created it).
11 Go to the left part of the Property inspector and assign an Instance name to this text field: call it info_txt.
In the same way as the Instance name suffix "_mc" informs Flash that you are talking about a movie clip, the suffix "_txt" tells Flash that the object you are referencing in your ActionScript code is a text field.
12 Lock the content layer. Create a new layer and call it actions.
Remember the following best practices when inserting ActionScript code into your movies:
- If possible, you should place all of your code in one layer. Reserve that layer for ActionScript code only — don't put any graphics or any kind of other objects inside it.
- Lock this layer. You can place your ActionScript code inside it without any problem while it is locked. Having it locked prevents you from accidentally placing objects inside it.
- Put this layer either on top of all the other layers in your movie or below them, so that you can easily find it when you need it.
That's all for the design part of this movie. Move on to ActionScripting!
Writing the ActionScript code that handles the user's interaction with the movie clips
13 Click on the first frame of the actions layer to select it for code input.
14 Choose Window > Actions (shortcut key: F9) to open the Actions window.
15 Enter the following code inside the Script pane (the big area below the buttons situated on top of the Actions window):
car_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
Right now this code can't do much. In fact, if you test your movie and click on the car_mc movie clip nothing will happen. This is because the function that handles what will appear in the info_txt text field has yet to be written. Before proceeding to that piece of code, let me explain you first the one you just entered.
The first line,
car_mc.onRelease = function() {
tells Flash what to do when a user clicks on the car_mc movie clip. This is done via the onRelease
event handler. An event handler tells Flash what to do when an event happens. An event is something that occurs while a SWF movie is playing: it can be the user clicking a button or rolling the cursor over a movie clip, a sound coming to its end, data being loaded etc.
The event handler used here, onRelease
, handles what happens when a user presses and releases the mouse button while the cursor is situated over the car_mc movie clip. This is what is considered a "standard" click: When you surf the Web, you click on various links. When you do that, you press your mouse button and release it.
In ActionScript there is also the onPress
event handler (among many others) that happens when the mouse button is just pressed. This is suitable for games, for example — when something has to happen instantly when the mouse is pressed — like a spaceship firing a shot. For buttons and interfaces the onRelease
event handler is just fine.
Back to the code, there is also an assignment operator (=
) and the keyword function
following it. What this does is that the function
is being assigned to the onRelease
event handler. This means when the car_mc movie clip is clicked upon, this function will be executed. What gets executed is all the code placed between the function's curly braces: {
and }
.
Here is the code between the curly braces:
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
The first line creates a variable called myName
and defines it as a String
type of variable. A String
type of a variable is one that holds a text value inside it. Next, you tell Flash that this variable will hold inside itself the name of the movie clip. How is that?
The piece of code this._name
makes this possible. The ActionScript keyword this
denotes (points to) the timeline or object it is placed upon. Yes, this code is placed on the main timeline, but since it is included in the car_mc movie clip's onRelease
event handler, it denotes the car_mc movie clip. So by writing this._name
, Flash reads this as car_mc._name
.
The _name
property of a movie clip refers to its Instance name. The final result of this line of code is that the myName
variable will hold inside itself the text car_mc
.
The next line creates a new variable of the String
type, called clicked
...
var clicked:String = myName.substr(0, -3);
...and stores inside it a new text value. This new value is a piece of text extracted from the myName
variable defined in the previous line of code. This is done via the substr
method. Let me show you how this works.
Suppose that you have a String
variable called myPhrase
with the following value:
var myPhrase:String = "Flash rules you all!";
If you wanted to extract the text "Flash" from this variable and place it in a new one, you could do it like this:
var myWord:String = myPhrase.substr(0, 5);
The value of the variable myWord
would be Flash
. The substr
method serves to extract a portion of an existing String
piece of data. It does so by reading the parameters between the parenthesis. In this example, the value of these parameters is 0 and 5.
The first parameter is the place in the string where the extraction will start. The second one is the number of characters that will be extracted. The following image explains this clearly:
As you can see, the first parameter (0 in this example) marks the index number — the position of the character inside the text where the extraction will start. And the first character inside a String value has always the index number zero. Don't confuse this with the second parameter which tells Flash how many characters to extract.
So the second parameter in this example is set to 5. This means that characters up to position 5 will be extracted, starting from zero: the characters with the index numbers 0, 1, 2, 3 and 4. And the result of extraction in this example is "Flash". Also, note that the spaces between words are also counted as any other characters are, therefore they have their index numbers too.
If you wanted to extract the text "rules you" for example, you would have to write substr(6, 9)
.
Back to this lesson's code, you have certainly noticed that a negative number (-3) is used in the substr
method:
var clicked:String = myName.substr(0, -3);
You use a negative number in as the second parameter in the substr
method when you want to specify up to which character the extraction should be done, but starting from the right side of the string. This means that the last character has the index position of -1.
So if you wanted to extract the word "Flash" from the phrase "Flash rules you all!" in this way, you would do it like this: substr (0, -15)
. NOTE: when using a negative number for the second parameter, the first one must be zero.
In this lesson, you will need to extract the name of each movie clip, without the suffix "_mc". So that's why this particular way of using the substr
method is used here. Since the Instance name of the first movie clip is car_mc, the string "car" will be extracted from it. Following this, "boat" will be extracted from boat_mc, "airplane" from airplane_mc and "island" from island_mc.
As you will make this text appear in the text field, it makes perfect sense to do it this way: there would be no sense in displaying a phrase like "you clicked on the car_mc". Instead, "you clicked on the car" is the text to be displayed.
Back to the code, there is just one remaining line of ActionScript inside the onRelease
event's function, shown in bold here:
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
16 This line calls the write
function (which has to be defined yet) and passes the clicked
variable to it. But more on this later. For now, add this functionality to the remaining three movie clips — write the following code immediately below the existing one:
boat_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
airplane_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
island_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
As you can see, when clicked upon, every movie clip performs the same exact task: it looks up its own name and stores it in a variable called myName
, then removes the suffix "_mc" from it with the use of the substr
method and then stores the new value in the clicked
variable. Finally, the write
function is called and the value of the variable clicked
is passed to it.
Since the same code is used four times, it makes sense to come up with some more concise and compact solution. You will see how to do that later, bet let me show you first how to use the switch/case conditional statement. Save your document.
Adding the function with the switch/case conditional statement
17 Add this code right after all the ActionScript written so far:
function write(clicked:String):Void {
switch (clicked) {
case "car" :
info_txt.text = "The "+clicked+" is a terrestrial vehicle.";
break;
case "boat" :
info_txt.text = "The "+clicked+" is a sea vehicle.";
break;
case "airplane" :
info_txt.text = "The "+clicked+" is an aerial vehicle.";
break;
default :
info_txt.text = "You haven't clicked on a vehicle.";
}
}
A function is a collection of data: various ActionScript commands and pieces of code put together that serves a purpose — a function is written to perform a certain task. But it just sits idly there unless you call it. The function call is being issued every time one of the four movie clips in this exercise is clicked:
write(clicked);
This function could be called like this, too: write();
— but in this example it would yield no results, because the function makes use of the clicked
variable. So the function call is made by passing a variable to it — the clicked
variable.
That's the reason this variable is mentioned in the opening line of the function:
function write(clicked:String):Void {
First you write the keyword function
, followed by its name (write
) and in the parenthesis is the variable (clicked
) that is being passed to it, along with its type (String
). You must specify the type of the variable passe to a function: this helps you check for any potential errors in your code, and if that happens, Flash will be able to notify you about it. Lastly, there is the Void
keyword, which signifies that this function does not return a value. Some functions do, some don't. And yes, if a function does not return a value, you should tell this Flash too.
The function used in this lesson serves for displaying some text in the dynamic text field. In case when a value is returned from the function, it is handed back over to whatever called it in the first place. And here, when a movie clip is clicked upon, it just passes a value to the function which then continues working on its own, without communicating back with movie clips.
As you remember from the previous page, the contents of a function are placed between its curly braces: {
and }
. The contents of the write
functions consist of a conditional switch/case statement:
switch (clicked) {
case "car" :
info_txt.text = "The "+clicked+" is a terrestrial vehicle.";
break;
case "boat" :
info_txt.text = "The "+clicked+" is a sea vehicle.";
break;
case "airplane" :
info_txt.text = "The "+clicked+" is an aerial vehicle.";
break;
default :
info_txt.text = "You haven't clicked on a vehicle.";
}
Let me explain you in detail how this nifty ActionScript construct works!
The functionality of the switch/case conditional statement explained
The first line of a switch/case logical construct,
switch (clicked) {
evaluates the piece of code between its parenthesis, which is a variable in most cases, as it is in this one too. As with the function, a switch/case conditional statement's code is placed between curly braces: {
and }
. Next, the value is being compared to the value of each case
line of code:
case "car" :
info_txt.text = "The "+clicked+" is a terrestrial vehicle.";
break;
case "boat" :
info_txt.text = "The "+clicked+" is a sea vehicle.";
break;
case "airplane" :
info_txt.text = "The "+clicked+" is an aerial vehicle.";
break;
If a match is found, the ActionScript contained inside that case
chunk of code is executed. Say, for example, that a user clicked on the boat_mc movie clip. As you recall, once this movie is clicked, it will look up its own Instance name, extract a string value (a piece of text) from it, and pass that value to the write
function. This function will in turn execute its own code, which is the conditional switch/case
statement I'm discussing right now.
So, a match is found:
case "boat" :
info_txt.text = "The "+clicked+" is a sea vehicle.";
break;
The line of code which displays text in the info_txt dynamic text field is executed.
info_txt.text = "The "+clicked+" is a sea vehicle.";
Translated into English, the construct info_txt.text
tells Flash "the text that will be displayed in the info_txt text field" is the one on the right side of the assignment operator (=
): "The "+clicked+" is a sea vehicle."
As the value of the clicked
variable equals "boat" if the user clicked on the boat movie clip, what will be displayed in the info_txt text field is "The boat is a sea vehicle". Flash reads this in the following way (translated into human language):
switch (have a look at this and evaluate it) {
if that value matches "car" :
Do this...
break;
if it happens to match "boat" :
Do this...
break;
if it matches "airplane" :
Do this...
break;
default (if a match is not found above):
Do this.
}
Ok, now you know how this works. Let's have a closer look at the details of a switch/case conditional statement. Like I said, the value between the parenthesis following the keyword switch
is evaluated and then compared to each case
statement. Once a match is found, the appropriate case
statement (the code contained within it) gets executed.
At the end of each case
statement there is a break
command. This prevents the next case
from being executed if a match is found. If a match is not found, the default
piece of code gets executed:
default :
info_txt.text = "You haven't clicked on a vehicle.";
18 Try it out: test your movie by selecting Control > Test Movie (shortcut key: Ctrl+Enter). Then click on each movie clip. If you click on any of the first three movie clips, a similar message will appear in the dynamic text field, depending on the particular case
statement. But when you click on the island_mc movie clip, the default
statement will be executed, with a different text being displayed in the text field.
Also, a nice thing that can be done with this conditional statement is to have Flash do the same thing for multiple cases. Say, for example, that you wanted Flash to display the same message each time one of the "vehicle" movie clips was clicked: "The [insert one of the three here] is a vehicle". You would do it like this:
switch (clicked) {
case "car" :
case "boat" :
case "airplane" :
info_txt.text = "The "+clicked+" is a vehicle.";
break;
default :
info_txt.text = "You haven't clicked on a vehicle.";
}
As you can see, there is only one break
statement here. So if any of the three cases is matched, the same line of code gets executed. If no match is found, the default
piece of code is run. Flash interprets this in the following way:
switch (have a look at this and evaluate it) {
if the value matches either "car" or "boat" or "airplane" :
Do this...
break;
default (if a match is not found above):
Do this.
}
This conditional logic is easy to use, isn't it? Sure it is! 🙂 Let me show you now why it is a better solution than using the if/else conditional statement in some cases.
The advantages of the switch/case conditional statement
Suppose that you wanted to use the if/else conditional logic in this exercice, instead of switch/case. Your code would look like this (I will show you the write
function only, since the rest of the code stays the same):
function write(clicked:String):Void {
if (clicked == "car") {
info_txt.text = "The "+clicked+" is a terrestrial vehicle.";
} else if (clicked == "boat") {
info_txt.text = "The "+clicked+" is a sea vehicle.";
} else if (clicked == "airplane") {
info_txt.text = "The "+clicked+" is an aerial vehicle.";
} else {
info_txt.text = "You haven't clicked on a vehicle.";
}
}
Clearly, this code is much less readable than the previous one. The switch/case logic is much easier to read, update and check for any potential errors.
In addition to readability, what is really important is the performance. The if/else logic evaluates each condition (if, else, else if, etc). In applications where there is a big amount of data that has to be evaluated, the switch/case statement has a significantly better performance (meaning a lesser load on the user's computer processor). This is because the value in the switch
statement gets evaluated only once.
You see now how efficient the switch/case logic can be. You will learn now how to make your code more compact, without any loss to the functionality of your SWF movie.
Cutting down the size of ActionScript code
The code that handles the user's clicking on movie clips currently looks like this:
car_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
boat_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
airplane_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
island_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
}
Obviously, the same exact code gets executed when each of these movie clips is clicked upon. Therefore, there is no sense at all in having so much code. Erase that code and type in the following one:
car_mc.onRelease = boat_mc.onRelease = airplane_mc.onRelease = island_mc.onRelease = function() {
var myName:String = this._name;
var clicked:String = myName.substr(0, -3);
write(clicked);
};
Ain't this much better? If you were to add or edit something, you can do it in one place instead of having to edit the code for each of these movie clips.
The new code functions exactly the same as the previous one. It says that the onRelease
event handler for each of these movie clips will do the same thing: run a function assigned to it.
I hope that you had fun learning from this lesson! To learn even more, be sure to check out my other ActionScript lessons. There are some cool things shown there, like the ActionScript-only clock, a slick dynamic mask effect and more. As always, you can download the source FLA file for this project below (it is in Flash MX 2004 format).
Download the source FLA file for the example shown at the start of this lesson.
really helpful tutorial!…….thankx
Thank you for your easy to understand explanation of this code. I think it will help me modified someone’s code.
I really understood your explanation. It is very useful for the begineers.
Thanks a lot.
good and interest
i am beginner in actionscript. And this tutorial really helpfull. Thanks
it easy way for all persons who knows about it