Monday, September 5, 2011

Flash FAQ: Communicating between Classes in AS3

I often answer questions on the forums over at and I noticed that people are always asking about communicating between classes. In particular, people ask how you can change a variable in the document class (main class) from another class. So instead of repeating myself, I'll post it here.

Short answer:  MovieClip.(this.parent).variable=xxx;

Long Answer:

You have to be careful when you access variables in one class from another class. Things can get confusing pretty quickly. But a good example of when it is kosher is when you have an enemy in a game; when it is hit by a bullet, it tells the document class to increase the score. It's simple and foolproof enough.

Okay, I set up a flash document with as the document class. I declare an object obj which is an instance of the class Obj. I declare a variable pvar, which we will set to 1 and then set to 2 by running a function in

package  {

import flash.display.MovieClip;

public class Main extends MovieClip {

public var obj:Obj;
public var pvar:int;

public function Main() {
obj = new Obj;addChild(obj);


Can you see that? It's easy to run a function on a separate class... we just say obj.ResetVar();

Of course, we haven't created yet, so let's do that now:

package {
import flash.display.MovieClip;
public class Obj extends MovieClip {

public function Obj() {}//Obj

public function ResetVar(){


Now you can see how we use the line MovieClip(this.parent).pvar=2; to refer to the parent of this movie clip and set pvar to 2.

Try it and you should get the trace '2'.

Got it? Good.

If you have any questions or the explanation isn't clear, please feel free to leave a comment. If you're looking for some more Flash tutorials or projects, try here:

No comments:

Post a Comment