Reputation: 353
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
Reputation: 39456
All DisplayObject
s that are part of the display tree (either directly on the stage or as a descendant of any DisplayObjectContainer
s on the stage) have access to root
, which will either refer to:
MainTimeline
if there is no document class 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