Search code examples
libgdx

LibGdx - Load skin from assetmanager


So I can load the skin in my assetManager like this:

manager.load(skinAtlas, TextureAtlas.class);
manager.load(menuSkin, Skin.class, new SkinLoader.SkinParameter(skinAtlas));

But if I want to add .ttf fonts at runtime how will I do this? i.e:

skin = new Skin();
skin.add("smallFont", smallFontT, BitmapFont.class);
skin.load(assetManager.getManager().get(assetManager.menuSkin, Skin.class)); //this does not work

Solution

  • If your Json styles don't rely on that particular font, you can add it to an existing skin at any time after you get the Skin object reference from the asset manager after the Skin has been loaded. Use skin.add("smallFont", smallFontT) to add your font to the existing skin.

    You can also specify other objects to add to the skin before the JSON file, so the JSON file can rely on them. But to do this with AssetManager, those assets must be loaded before the AssetManager loads the JSON file to a Skin.

    So you could first load those assets directly without an AssetManager, or you could load them using the AssetManager (add them to the manager and finishLoading on the manager before adding the skin to the manager). Either way, you need to get a reference to each of the assets your JSON will need to reference.

    Then put them in an ObjectMap. For example:

    ObjectMap<String, Object> resources = new ObjectMap<String, Object>();
    resources.put("smallFont", smallFontT); //assuming smallFontT is a reference to a BitmapFont object
    

    Then these resources can be put into your SkinParameter:

    manager.load(skinAtlas, TextureAtlas.class); //I'm assuming skinAtlas is a String path to your atlas
    manager.load(menuSkin, Skin.class, new SkinLoader.SkinParameter(skinAtlas, resources));
    

    Now styles in your JSON can reference a font by the name "smallFont".