Sunday, May 17, 2015

Arrays with Actionscript 3.0

An array is a list of items that can be used as variables. Rather than declare each variable separately, we do it all at once with an array. In this exercise we will experiment with a simple array to see how one works.

The Basics 

To begin, we'll create an array that contains a list of words. Then we'll use a button to retrieve one of those words from the list.


  • Open a new Flash file and save it right away as yourName_arrayEx.fla
  • On the main timeline create a dynamic text box large enough to hold a single, long word. Give the text box the instance name output_txt.
  • Create a simple button symbol. Give it the instance name getWord_btn.
  • Create a new layer and call it actions.
  • Select the keyframe in the actions layer and open the Actions window. We'll begin the script by declaring and filling our array: 
var myList:Array=new Array("red","orange","yellow","green","blue","purple"); 
  • The above syntax is one way you can declare an array. You can also create an array by using an array literal which looks like this :
var myList:Array=["red","orange","yellow","green","blue","purple"];  
  • Both methods work equally well; the one you use is more or less a matter of preference. Here's another variation that also works :
var myList:Array=new Array();
// lots of code can go between these lines  
myList=["red","orange","yellow","green","blue","purple"];  
  • This method allows you to create an empty array with the first line, and then fill it at a later point in the code.
  • For now pick one of the above methods to use.
  • Now add a listener for the button :
getWord_btn.addEventListener(MouseEvent.CLICK, getWord);   
  • And now the function called by the button listener :
function getWord(myEvent:MouseEvent) {
    output_txt.text=myList[3];     
}  
Try it out. When you hit the button, the word "green" should appear in the text box. But wait a sec—why green? Green is the fourth word, not third, and the function calls the third object in the array, right? Well, not exactly; Flash (and most computer programs) starts counting at zero. Thus, red is word 0, orange is 1, yellow is 2 and green is 3. Confusing? Don't worry, you'll get used to it.

Source : http://www.danfergusdesign.com


Location: United states

0 comments:

Post a Comment

Popular Posts

Categories

tutorial-nia. Powered by Blogger.