Global variables are useful when you want a variable to be accessible from
anywhere in your movie, even in different scenes. It's also a good thing to
declare a variable as global rather than put it in the _root, because putting
everything there can cause some problems. Of course, you have to be sure that
there is no other variable called like that somewhere else in the movie.
The syntax is quite simple - all you have to do is add
_global in front of the variable.
- _global.myVar=5;
Simple. But as always, you have to be careful. If you want to change, or
access this variable, you have to put _global in
front too.
- trace (_global.myVar);
- // returns 5
Actually, if you don't put _global, it will
also work. But let's look at this example:
- _global.myVar=5;
-
- for (i=0;i<5;i++)
- {
- myVar++;
- }
-
- trace (myVar);
- // returns 10
- trace (_global.myVar);
- // returns 5
Mmm? What happened? Why is the result different?
Let's look at what we did. First we initialize a global variable to 5, and
then we increment in a for loop the variable without the keyword
_global in front. And when we trace the
variables, with and without _global, they have
different values.
Not putting _global made Flash create a variable
in the variable space of the timeline, giving it the default value of the global
variable, and masking the global variable in this timeline. That's why we don't
manipulate the global variable, but the local variable.