I am making a program using the amazing libGDX
+scene2d API and I structured it as follows:
- I have a single
MyGame
instance, holding a singlePolygonSpriteBatch
instance. - There is an abstract
MyScreen
class, holding aMyStage
class (see below) - Then there are lots of different screen classes that inherit from
MyScreen
, and instantiate each other at will.
(in all cases, removing the "My
" gives you the name of the respective library class that it extends)
This model worked fine, until I encountered some problems to perform actions between screens using the Action
system. I decided then that it would be a good idea to have a single OmnipresentActor
belonging to MyGame
that, as the name says, is present in every scene. So I modified MyStage to look more or less like this:
public class MyStage extends Stage {
public MyStage(MyGame g) {
super(new FitViewport(MyGame.WIDTH, MyGame.HEIGHT), g.batch);
addActor(game.omnipresentInvisibleActor);
}
@Override
public void clear() {
unfocusAll();
getRoot().clearActions();
getRoot().clearListeners();
removeActorsButNotListenersNorActions();
}
public void removeActorsButNotListenersNorActions() {
for (Actor a : getActors()) if (a.getClass()!= OmnipresentInvisibleActor.class) a.remove();
}
It followed a painful debugging phase, until I found out the following:
public PresentationScreen(MyGame g) {
// super() call and other irrelevant/already debugged code
System.out.println("PRINT_BEFORE: "+ stage.getActors().toString()); // OmnipresentActor is there
mainMenuScreen = new MainMenuScreen(game);
System.out.println("PRINT_AFTER: "+ stage.getActors().toString()); // OmnipresentActor is not there anymore, but was added to the mainMenuScreen
the "PRINT_BEFORE"
statement shows that the stage
holds the omnipresentActor
. In "PRINT_AFTER"
it isn't there anymore, whereas mainMenuScreen
is indeed holding it. So my question, now more precise:
does scene2d prevent this to happen, or am I doing something wrong here?
Answers much appreciated! Cheers