我们之前的代码如果有用到纹理、音乐、字体等资源时,都是现用现加载的,而且是同步式的,这在实际开发中肯定不行,因为我们的素材资源会非常庞大,实现资源预加载和缓存、资源复用、资源异步加载能显著提升用户体验。
LibGDX提供了AssetManager
能够实现资源的统一管理。
下面例子中,我们的Game
类实现了单例模式,并关联了一个AssetManager
,这样便于在其他位置对资源加载器进行引用,演示了使用AssetManager
加载纹理、音乐、瓦片地图的方法。注意,瓦片地图需要手动指定加载器,如果我们有自定义的资源类型,也可以编写自己的加载器。
package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
public class GdxGame extends Game {
private static GdxGame self = null;
private MainScreen mainScreen;
private AssetManager assetManager;
private GdxGame() {
super();
self = this;
}
public static GdxGame getInstance() {
if (self == null) {
self = new GdxGame();
}
return self;
}
@Override
public void create() {
// 初始化资源
assetManager = new AssetManager();
assetManager.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver()));
assetManager.load("map/map.tmx", TiledMap.class);
assetManager.load("actor.png", Texture.class);
assetManager.load("test.mp3", Music.class);
new Thread() {
@Override
public void run() {
while (assetManager.getProgress() != 1) {
System.out.println(assetManager.getProgress() * 100 + "%");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
assetManager.finishLoading();
// 初始化stage
mainScreen = new MainScreen();
setScreen(mainScreen);
}
public MainScreen getMainScreen() {
return mainScreen;
}
public AssetManager getAssetManager() {
return assetManager;
}
@Override
public void render() {
super.render();
}
}
代码比较简陋,其实就是在资源加载的过程中,阻塞当前线程,然后单开一个线程在控制台上打印当前资源加载的进度,进度通过assetManager.getProgress()
获取,实际开发中我们一般都是做个进度条,也不需要阻塞当前线程,这里就不搞那么麻烦了。
获取资源比较简单,直接用assetManager.get()
即可,参数是资源路径。这里就不贴完整代码了,直接给出几个例子:
TiledMap map = GdxGame.getInstance().getAssetManager().get("map/map.tmx");
Texture texture = GdxGame.getInstance().getAssetManager().get("actor.png");