In the
previous page we created the flash file that randomly picked out a
quote from an external text file. In this page I will explain the
ActionScript used, and also the how to format the text file so
Flash can read it correctly.
The ActionScript:
- ranQuote
= new
LoadVars();
This line creates a new LoadVars variable
ranQuote a LoadVars variable allows you to load variable
to use in flash from an external source in our case a text file.
- ranQuote.onLoad
= function(success)
{
- if
(success)
{
- RanNum
= Math.ceil(Math.random()*5);
- ran
= this["quote"+RanNum];
- quote_txt.text
= ran;
- }
This bit of code test to see if the text file is loaded and acts accordingly. If the if statement returns
success
which is a boolean (true or flase), the code in side the if statement will get executed. This is where the it generates the random number and picks out
a quote to display. So lets dissect the if statement further and explain what is going on:
- RanNum =
Math.ceil(Math.random()*5);
This line the variable RanNum is created and it generates a number between 1 and 5 by using
Math.ceil() it will round up the number so as you never get a zero
any decimal places in your random number. The Math.random()*5 is self explanatory if you want to generate more numbers, you would change the 5 to however many quotes
you have in your text file.
- ran =
this["quote"+RanNum];
We have a random number stored in a variable now, and now we need that number to assign to the
quote variable inside the text file.
we create the ran array and attach the random number to our "quote" variable.
- quote_txt.text
= ran;
This is what displays the random quote into the text field by using the instance name,
quote_txt, we assigned to it in the previous page. It then takes the array
ran and uses that to know which quote to display from the text file.
- else {
- quote_txt.text
= "The text failed to load due to an error";
- }
This bit of code is only executed if the text fails to load and displays the custom error message in the text field. You can
of course change the error message to what ever you like.
- ranQuote.load("Quotes.txt");
- stop();
These second last line is the all important line that loads the actual text file for flash to reference the external
variables. The last line is of course self explanatory.
Text File Formatting
Now we have explained the ActionScript, I will show you how to format your text file:
The variables must have no space between in the equals sign(=) and the actual quote you want to be displayed.
E.g. quote1=This is a quote
Now when we want to have more than one variable in a single text file they must be
separated by an ampersand(&) with no spaces.
E.g.
quote1=blahblahblah"e2=blahblah
Your done if your having problems, download the source file
so you can see what exactly went wrong.
If you having any issues don't be afraid to check out the
Kirupa Forums and ask any questions you may have.
Cheers!
 |
Ryan Seddon aka
Inept
|
 |
page 2 of
2 |
|