Thursday, 23 July 2009

Load external text in Actionscript 3

In this tutorial you will learn how to load external text into a dynamic text field in Flash. You will need to use the URLRequest and the URLLoader classes. The URLRequest class is used to capture all the request information, and the URLLoader is used to load up the request information. More information on these classes can be found at the AS3 component reference.


Load external text in Actionscript 3.0

Step 1

Open a Flash AS3 file.
Then open up notepad or an equivalent program and write the message: “This is externally loaded text” and save the file with the name “external_text” in the same location as the fla file.




Step 2

Select the text tool and drag and dynamic text field on the stage like below:




Step 3

Using the selection tool (V) select the dynamic text field and give the following instance name: “my_txt” as shown below:




Step 4

On the timeline insert a new layer called “Actions”. Select the first frame and hit F9 to open the Actions panel and enter the following code:

//1.
var my_req:URLRequest = new URLRequest("external_text.txt");
var my_loader:URLLoader = new URLLoader();

//2.
my_loader.addEventListener(Event.COMPLETE, loadText);
my_loader.load(my_req);

//3.
function loadText(event:Event):void{
my_txt.text = my_loader.data;
}

Code:
1. This creates new instances of the URLRequest and the URLLoader classes. Note that the URLRequest has the name of the text file inside the parenthesis. The text file also has to be in the same location as fla file.
2. This is an event listener to listen to when the text file has finished loading using the ‘Event.COMPLETE’ event. The load method receives the data from the text file.
3. This is the load text function sets the text from the text file to the dynamic text field.


Step 5

Test your loaded external text Ctrl + Enter. You should get the following message below:


You should now be able to load external text.

2 comments:

abdul 2 August 2011 00:49  

this code is so good,
but i m trouble in copy of code in other frames,
its error duplicate function,
it changed my_txt to me_txt for other, but also its error, how i can copy it same or other frame.?

iliketo 22 October 2011 00:15  

@Abul,

Change the name of the variables.

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP