1

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.

senor tee
  • 47
  • 9
  • For a class to access "stage" it has to be on the stage else it is null. For a class to access "addChild" or any display type functions it has to inherit display object methods usually done by extending sprite. – The_asMan Jan 31 '12 at 16:19
  • My class does extend sprite and is imported into main class. Is the import statement itself not enough? Does this mean it is not on the stage? – senor tee Jan 31 '12 at 16:24
  • I have updated my question with code if that helps. – senor tee Jan 31 '12 at 16:59

2 Answers2

3

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)
turbosqel
  • 1,542
  • 11
  • 20
2

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
bummzack
  • 5,805
  • 1
  • 26
  • 45