haxeaddchildopenfl

OpenFL - How to use addChild in another class?


The answer should be simple but I can't find out how anywhere..

So I have a Main.hx class and a ObjectManager.hx class. In the main class's constructor, it calls ObjectManager.addAllToScreen(); and my objectManager should then add the objects to the screen.

I thought this would be ok because in the constructor of Main you can just say addChild(Objects.platform); but apparently addChild isn't accessible?

The error is: Class<Main> has no field addChild so I'd guess that addChild is a method of Sprite or something?

package;

class Main extends Sprite {
    public function new() {
        super();
        ObjectManager.addAllToScreen();
    }
}

In ObjectManager:

package;

class ObjectManager {
    public static function addAllToScreen():Void {
        Main.addChild(Objects.platform);
        Main.addChild(Objects.messageField);
    }
}

UPDATE:

Ok so now the code is this... and it runs just fine apart from the objects never showing up on screen - however if the addChild code is put in main, they do show up.

Main:

class Main extends Sprite {

public function new() {
    super();
    var objectManager = new ObjectManager();
    objectManager.addAllToScreen();
}

ObjectManager:

package;
import openfl.display.Sprite;    

class ObjectManager extends Sprite {
    public function new() {
        super();
    }
    public function addAllToScreen() {
        addChild(Objects.platform);
        addChild(Objects.messageField);
    }
}

Solution

  • addChild() is available in openfl.DisplayObjectContainer, which Sprite extends. So you would need to make your class extend Sprite, yes.