Flash CS5 reference a display object in the constructor of a non-document class

后端 未结 3 1499
感动是毒
感动是毒 2021-01-25 02:17

After learning of this excellent method of accessing an object placed on the stage in Flash CS5 in a class other than the document class (found in this thread), I have run into

3条回答
  •  忘掉有多难
    2021-01-25 03:15

    stage is a property of DisplayObject only accessible/defined once it has been added to the DisplayList (ie - added to something via addChild())

    You won't have any luck accessing stage from a class constructor unless it's the document class.

    As mentioned, you can shift the contents of your constructor to a custom function which is called once Event.ADDED_TO_STAGE has been triggered.

    For example, here's a demo class:

    public class Thing extends DisplayObject
    {
        /**
         * Constructor
         */
        public function Thing()
        {
            // Add listener
            addEventListener(Event.ADDED_TO_STAGE, _added);
        }
    
        /**
         * Called once this has been added to the display list
         * @param e Event.ADDED_TO_STAGE
         */
        private function _added(e:Event):void
        {
            // Discard listener
            removeEventListener(Event.ADDED_TO_STAGE, _added);
    
            // My initial code
            trace(stage + " is accessible");
        }
    }
    

    Which we then create an instance of:

    var thing:Thing = new Thing(); // nothing happens
    

    And then add to the stage/current container:

    addChild(thing); // output: [Object Stage] is accessible
    

    As for accessing greenLight1, this should be achievable easily via either of the following:

    stage.greenLight1;
    stage["greenLight1"];
    

    Also, you might want to replace:

    public function Player(stage:Object):void
    

    With:

    public function Player(stage:Stage):void
    

提交回复
热议问题