Search code examples
androidlibgdxtextures

libGDX: Create TextButton with TextureRegion


I have a class where I load all my TextureRegions.

public class AssetLoader{

    public static TextureAtlas atlas;
    public static TextureRegion startButtonUp;
    public static TextureRegion startButtonDown;
    ...


    public static void loadAssets(){
        atlas = new TextureAtlas("images.atlas");   
        startButtonUp = atlas.findRegion("start_button_up");
        startButtonDown = atlas.findRegion("start_button_down");
    }
}

Now I want to create a TextButton in different classes which uses the TextureRegion from my AssetLoader. My actual workflow is:

    buttonsAtlas = new TextureAtlas("images.atlas");
    buttonSkin = new Skin();
    buttonSkin.addRegions(buttonsAtlas);

    font = new BitmapFont();

    stage = new Stage(new FitViewport(800, 400, camera), game.batch);

    Gdx.input.setInputProcessor(stage);

    textButtonStyle = new TextButton.TextButtonStyle();

    textButtonStyle.up = buttonSkin.getDrawable("start_button_up");
    textButtonStyle.down = buttonSkin.getDrawable("start_button_down");

    textButtonStyle.font = font;

    button = new TextButton("Start", textButtonStyle);
    button.setHeight(AssetLoader.startButtonDown.getRegionHeight());
    button.setWidth(AssetLoader.startButtonDown.getRegionWidth());

    button.setPosition(0,100);

    stage.addActor(button);
    button.addListener(new ClickListener() {
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            /// start game
            game.setScreen(new PlayScreen(game));
            dispose();
        }
    });

But in this case I don't really need my AssetsLoader (expect the RegionWidth and RegionHeight) and it seems like a lot of code for every button in different classes. Is there any solution to solve this problem more efficient?


Solution

  • AssetLoader class having a textureAtlas and reference of two TextureRegion that is inside that textureAtlas.

    If you want to rely on AssetLoader, create object of AssetLoader and use atlas of AssetLoader instead of buttonsAtlas(a new instance of textureAtlas).

    or forget AssetLoader

    button = new TextButton("Start", textButtonStyle);
    button.setHeight(buttonsAtlas.findRegion("start_button_up").getRegionHeight());
    button.setWidth(buttonsAtlas.findRegion("start_button_up").getRegionWidth());
    

    It's good way to create all assets in one class and use all over the game, If possible you should use AssetManager in your game.