Tuesday, July 13, 2010

Reading variables from text file in AS3

This post will explain how to read data from variables stored in a text file.

The format of the text file will be as follows -

var_1=first variable&var_2=second variable

You can have any number of variables defined in this text file.

The AS3 code will be as follows -

var loader:URLLoader = new URLLoader();

//telling the loader that we are dealing with variables here.
loader.dataFormat = URLLoaderDataFormat.VARIABLES;

loader.addEventListener(Event.COMPLETE, loading);

//Name of the text file to load.
loader.load(new URLRequest("content.txt"));

//news_1 & news_2 are the dynamic text fields on the stage to display the values being read.
function loading (event:Event):void {
news_1.text = loader.data.var_1
news_2.text = loader.data.var_2

So with the above mentioned code we can read the values of var_1 and var_2 stored in the text file and populate the .text property of the dynamic text boxes sitting on stage to display those values.