R – when does the stage become initialised

actionscript-3

I have a singleton class that inherits from sprite so that it can access the stage, like this..

package  
{
    import flash.display.Sprite;

    public class C extends Sprite
    {   
        private var _grid:Array = new Array();

        public function get Grid():Array
        {
            return _grid;
        }       

        private static var _instance:C;

        public static function get Instance():C
        {
            if (_instance == null)
            {
                _instance = new C();
            }

            return _instance;
        }

        function C() 
        {
            this.InitGrid();
        }

        private function InitGrid():void 
        {
            var gridWidth:Number = stage.width / 10;
        }
    }
}

This throws the error

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at C/InitGrid()
    at C()
    at C$/get Instance()
    at C()
    at Main()

If I replace stage.width with an int the code executes OK.
is this because the object has not been added to the displayList of any children of the stage?

Thanks

Best Answer

Yes. The Sprite will only have a stage property once it's a part of the Display list.
To get the stage you will need to either give your singleton a reference to the stage or add it to the Display list. If you choose the latter you can add a listener Event.ADDED_TO_STAGE, and handle that accordingly inside your singleton.

Related Topic