Koden
Koden

Reputation: 353

how to access a variable on main timeline from a class in AS3?

I have seen several posts of this same question asked and there is no clear answer.

main timeline:

var mynum:Number = 0;

How would I access/alter this variable from the code in an external class file? Everything I try returns the "instance does not exist error"

Upvotes: 0

Views: 304

Answers (1)

Marty
Marty

Reputation: 39456

All DisplayObjects that are part of the display tree (either directly on the stage or as a descendant of any DisplayObjectContainers on the stage) have access to root, which will either refer to:

  1. The MainTimeline if there is no document class present.
  2. The document class if one is present.

Casting root to MovieClip will make it be treated as dynamic, meaning variables and functions that you declare on the main timeline will be accessible without compile-time errors, meaning you can do this:

trace(MovieClip(root).mynum);

Because the child has to be on the stage at the time of the code being executed, this cannot be placed directly in the constructor for objects that are added dynamically with addChild. However, you can leverage the ADDED_TO_STAGE event to wait for the object to be added to the stage first:

public class Example extends Sprite {
  public function Example() {
    addEventListener(Event.ADDED_TO_STAGE, added);
  }

  protected function added(event:Event):void {
    trace(MovieClip(root).mynum);
  }
}

Upvotes: 1

Related Questions