I’ve been running into a lot of problems with using fonts recently, so here’s another problem I encountered when I was trying to use an AssetManager to help me managet my BitmapFont class.
If you looked up something similar to Libgdx asset manager font on Google you might find the link to the AssetManager wiki and while it explained most things for me, there were some confusions that I had (and some misunderstandings) that took me a long time to finally resolve.
When trying to create your AssetManager, some errors you might encounter are these:
com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader$FreeTypeFontLoaderParameter cannot be cast to com.badlogic.gdx.assets.loaders.BitmapFontLoader$BitmapFontParameter
com.badlogic.gdx.utils.GdxRuntimeException: Asset not loaded
After an hour of debugging and searching around I finally found the conclusion.
As you might know following the documentation, we get to the point when we’re adding a font type here:
// First, let's define the params and then load our smaller font FreeTypeFontLoaderParameter mySmallFont = new FreeTypeFontLoaderParameter(); mySmallFont.fontFileName = "arial.ttf"; mySmallFont.fontParameters.size = 10; manager.load("arial.ttf", BitmapFont.class, mySmallFont); // Next, let's define the params and then load our bigger font FreeTypeFontLoaderParameter myBigFont = new FreeTypeFontLoaderParameter(); myBigFont.fontFileName = "georgia.ttf"; myBigFont.fontParameters.size = 20; manager.load("georgia.ttf", BitmapFont.class, myBigFont);
So, what happens if you have Parameters that require the same font type? And which part is the part that specify the file location?
Looking at the previous examples it seemed like we’d do it in the load function:
manager.load("data/mytexture.png", Texture.class); manager.load("data/myfont.fnt", BitmapFont.class); manager.load("data/mymusic.ogg", Music.class);
But it turns out that’s not the case.
Here’s a checklist of what you have to do to get your code to work and resolve the errors above.
- fontFileName is in fact the file location of your font. Wherever you would normally use with Gdx.files.internal(), you would use the same thing
- the string you put in the load() function is just how you map your font to the one you use, so it can be whatever you want however you MUST end the name with a .ttf extension. Otherwise you’ll get the same errors mentioned above.
- Finally, for those who missed it in the documentation. All load() does is it queue’s your assets to be loaded, it doesn’t load the files yet. You have to call the assetManager.finishLoading() function to call to start the process of loading all of your data (or finishLoadingAsset() for your specific asset)
Hopefully if you encountered these problems, these 3 points above will help you resolve your problem. As a reference, here’s some sample code from my project that might give a more concrete example.