4

In ActionScript 3, I've read that the root variable references an instance of the Document Class.

Within my document class constructor, a trace(this == root) returns true. Later in the constructor, a constructor of another class is called. This constructor, however, states that root is null. Finally, tracing from an event listener gives me the result that root is [object Stage].

My goal is to have a single instance of a Document Class (in MainGame.as) and to be able to refer to that as (root as MainGame) throughout my ActionScript program. How can I do this?

If it matters, all of my code is in the default package.

Thanks!

Community
  • 1
  • 1
wchargin
  • 15,589
  • 12
  • 71
  • 110
  • You can alternatively pass the root or stage in the constructor of your class (the one other than the document class) if you don't want to add the instance to the stage right away. That will allow you to use some properties that are bound to the root/stage itself. – inhan Jan 29 '13 at 22:49

1 Answers1

5

The root propety of a DisplayObject becomes a reference to the Document Class once the DisplayObject is added to the display list. You can continue to use root but be aware that only objects on the display list will work.

You can read more about root here:

The root property of the Stage object is the Stage object itself. The root property is set to null for any display object that has not been added to the display list, unless it has been added to a display object container that is off the display list but that is a child of the top-most display object in a loaded SWF file.

Foggzie
  • 9,691
  • 1
  • 31
  • 48
  • If I have an object on the stage, isn't it automatically on the display list? Thus, shouldn't the `root` property be a reference to the Document Class, instead of the stage? – wchargin Jan 29 '13 at 20:58
  • 3
    When the constructor of the other class is called it isn't yet added to the display list. You have to listen for `Event.ADDED_TO_STAGE` and then trace the root in the event handler. – Chunky Chunk Jan 29 '13 at 21:16