Flash CS4 ActionScript 3.0 Tutorial
How to Output ActionScript Text to the User
Dynamic text is used to output information from ActionScript to the user.
In this example we will create a random number generator. Each time the user presses the Roll button, another value is displayed in the Dynamic text field.
Dynamic Text box with instance name of outText_txt
Button Symbol with instance name of roll_btn
Open a new Flash document and add a new layer.
Name the upper layer Actions and the lower layer Content.
Click the keyframe for the Content layer.
Add an empty Dynamic text block to the stage. Choose Dynamic text In the Properties panel.
Click the Dynamic text box and assign it an instance name of outText_txt in the Properties panel.
Add a button symbol to the Content layer and assign it an instance name of roll_btn in the Properties panel. For more information on creating buttons, see topic, Button Symbol Basics.
Option double-click (PC - Alt double-click) the keyframe of the actions layer to open the ActionScript panel.
Copy/Paste the following code to the ActionScript panel.
var rollValue:uint = 0;
rollValue = 100*Math.random();
outText_txt.text = String(rollValue);
Click the Auto Format button to format the code
Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Each time you press the Roll button, a new random number displays in the Dynamic text field.
Dissecting the Code
The first line of code establishes a new positive integer variable named rollValue and sets its value to zero. The next line adds an Event Listener to the button. It needs to know if the button has been clicked. Once the user clicks the button, the function newRoll is told to run.
The code inside the curly braces of the function determines what the function will do. The rollValue line creates a random number between zero and one. That number is multiplied by 100 so your random values are whole numbers between zero and 100.
The final line of code interprets the rollValue as a String and places that value in the Dynamic text field with the instance name of outText_txt.