Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done
Look, an author!

Global Variables

by ilyas usal   | filed under Flash and ActionScript

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.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.

Your support keeps this site going! 😇

- pom

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--