02.02.2013 Views

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7: So what is a variable?<br />

But, what if you do not know the name of the object until the player clicks on a but<strong>to</strong>n? By<br />

clicking on the but<strong>to</strong>n the user can set the value of a variable you have created called charName,<br />

<strong>to</strong> ‘<strong>Art</strong>hur’. Now ‘<strong>Art</strong>hur’ is a string that is s<strong>to</strong>red in the variable charName. So how do you use<br />

the charName <strong>to</strong> access the value of feet in the object called <strong>Art</strong>hur? If you use<br />

charName.feet;<br />

this does not access the object; instead it accesses the string called charName. This does not have<br />

a feet setting so <strong>Flash</strong> would return zero or, with strict data typing, an error.<br />

1 var <strong>Art</strong>hur:Object = new Object();<br />

2 <strong>Art</strong>hur.feet = 12;<br />

3 var charName:String = "<strong>Art</strong>hur";<br />

4 trace(charName.feet);<br />

Listing 7.9<br />

The program shown in Listing 7.9 would result in the error message shown in Figure 7.9.<br />

Figure 7.9 Output from Listing 7.9<br />

Instead you want <strong>to</strong> get at the object named ‘<strong>Art</strong>hur’. This is achieved with the ‘eval’ keyword:<br />

eval("charName").feet;<br />

The function eval takes a string parameter and returns a variable or object with that name<br />

if it exists. The eval function can also be very useful for accessing movie clip instances<br />

when you have many copies of a movie clip all with names that include a number: Ball0,<br />

Ball1 ... Ball12. If you want <strong>to</strong> apply the same code <strong>to</strong> each instance then you would build<br />

99

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!