AS3无法访问空对象引用的属性或方法

时间:2014-04-09 10:54:46

标签: actionscript-3 class

我一直在每个网站上搜索此类错误,但尚未找到任何解决方法。错误发生在Gold _money.addText(stage);类中让我更加困惑的是,在_money.addText(stage);类中调用Main时,它可以正常运行而不会出现任何错误。请帮忙。谢谢!

另外我想问的另一件事。在Gold班。我试着跟踪,看看钱的计数如何。无论我点击了多少金币,它都会保持在5。我想知道为什么它不会增加?

以下是金级:

package
{

    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Gold extends MovieClip
    {
        private var _main:Main
         private var gold:Gold;
        public var destinationY:int;

        private var _money:Money =  new Money();


        public function Gold(main:Main):void 
        {

                          _main=main;
            addEventListener(MouseEvent.CLICK, goldClicked);

        }

        private function goldClicked(e:MouseEvent):void
        {
            e.currentTarget.removeEventListener(MouseEvent.CLICK,goldClicked);
                 _main.goldContainer.removeChild(e.currentTarget as Gold);
            _money.money+=5;
            trace(_money.money);
            _money.addText(stage);
        }

    }
}

这是Money类:

package
{   

    import flash.text.TextField

    public class Money
    {
        public var money:int;
        private var moneyText:TextField =  new TextField();

        public function Money():void
        {

        }

        public function addText(stage:Object):void
        {
            stage.addChild(moneyText);
            moneyText.x = 5;
            moneyText.y = 5;
            moneyText.height = 20;
            moneyText.textColor=0x000000;
            updateMoney();
        }
         public function updateMoney():void {
            moneyText.text="Money: "
        }
    }
}

Main class的某些部分:

package
{   

    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.events.Event;


    public class Main extends MovieClip
    {
        private var field:Array;
        public var gold:Gold;
        public var goldContainer:Sprite = new Sprite();
        private var goldTimer:Timer = new Timer(2000);
        public var _money:Money = new Money();

        public function Main():void
        {
            setupField();
            _money.addText(stage);
            goldSet();
            addEventListener(Event.ENTER_FRAME,onEnterFrm);
        }
    }   
}

1 个答案:

答案 0 :(得分:0)

在显示对象中,在将其添加到舞台之前,您无权访问舞台。所以你需要等待那个事件。

更改

    public function Main():void
    {
        setupField();
        _money.addText(stage);
        goldSet();
        addEventListener(Event.ENTER_FRAME,onEnterFrm);
    }

    public function Main():void
    {
        this.addEventListener(Event.ADDED_TO_STAGE, onStage)
    }

    public function onStage(e:event):void{
        this.removeEventListener(Event.ADDED_TO_STAGE, onStage)
        setupField();
        _money.addText(stage);
        goldSet();
        addEventListener(Event.ENTER_FRAME,onEnterFrm);
    }