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.
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