AS3 Global class that can add objects to stage

我的未来我决定 提交于 2020-01-06 03:30:31

问题


So I recently learnt that by importing a class into my main class I can access its functions from any other class. BUT.... one of my functions in the imported class needs to add display objects to the stage. I accessed the static function just fine but it can't add objects to the stage. It doesn't even seem to recognise addChild. Is this because it is not in the display list itself?

What am I missing here? How would you guys solve this issue. I was so close, yet so far!

Code is like this:

package {

import flash.display.Sprite;
import PopHandler;

public class MyMainClass extends Sprite {
    public function MyMainClass():void {
        PopHandler.LaunchPop();
    }
}

}

This is the imported class that doesn't add anything to stage.

package {
import flash.display.Sprite;

public class PopHandler extends Sprite {

    public function PopHandler():void {

    }

    public static function LaunchPop() {
        var bp:BreakPop = new BreakPop();
        bp.x = 500;
        bp.y = 347;
        addChild(bp);
    }
}   

}

BreakPop being an item in my library.

Thanks in advance.


回答1:


Since you're using a static method, your PopHandler isn't an instance of a sprite and therefore doesn't have access to the stage property. If you want to leave it as a static method, then you can basically skip the extends Sprite and just go for public class PopHandler {

That out of the way, here's a simple solution to your problem: Why not pass the DisplayObjectContainer you'd like to add the BreakPop to as a parameter of your static method?

Example:

public static function LaunchPop(target:DisplayObjectContainer) {
    var bp:BreakPop = new BreakPop();
    bp.x = 500;
    bp.y = 347;
    target.addChild(bp);
}

Then you call it like this (some examples):

PopHandler.LaunchPop(this); // <-- adding to current object
PopHandler.LaunchPop(root as DisplayObjectContainer); // <-- adding to root
PopHandler.LaunchPop(stage); // <-- adding to stage



回答2:


extend You main document class and add there static var , than assing stage on init :

public class Main extends MovieClip {

   public static var stage:Stage;

   public function Main ():void {
     Main.stage = stage;
   }
}

and then anywhere in app You can access to stage :

Main.stage.addChild(element)


来源:https://stackoverflow.com/questions/9082820/as3-global-class-that-can-add-objects-to-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!