Andengine基础笔记之resource manager

在这一节,我们讨论一下我们的资源管理,通过资源管理的类,我们可以轻松的通过调用方法,比如loadTextures(),loadSounds(),或者是loadFonts(),进而加载不同类型的资源。

资源管理类使用单例模式,其允许全局的调用,仅仅需通过调用ResourceManager.getInstance().ResourceManager最主要的目标就是加载资源,卸载资源。

下面的代码展示了ResourceManager是如何处理纹理图片的。

1、定义所有在不同场景中要使用的资源。

 public ITextureRegion mGameBackgroundTextureRegion;

public ITextureRegion mMenuBackgroundTextureRegion;

public Sound mSound;

public Font mFont;

2、实现load()方法,可以加载类中定义的音频、图形、字体资源。

public synchronized void loadGameTexture(Engine pEngine,Context pContext){

BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/game/");

BuildableBitmapTextureAtlas mBitmapTextureAtlas=new BuildableBitmapTextures(pEngine.getTextureManager(),800,480);

mGameTextureAtlasTextureRegion=BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmpTextureAtlas,pContext,"game_background.png");

mBitmapTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource,BitmapTextureAtlas>(0,1,1));

mBitmapTextureAtlas.load();

}

3、第三步包括提供方法卸载无用资源

public synchronized void unloadGameTextures(){

BuildableTextureAtlas mBitmapTextureAtlas=(BuildableBitmapTextureAltas)mGameBackgroundTextureRegion.getTexture();

mBitmapTextureAtlas.unload();

//....所有的卸载资源的代码..../

System.gc();//一但所有无用资源都卸载掉了,那么就可以调用系统的回收方法。

}

通过实现ResourceManager类,我们很简单的独立加载资源而不影响其它。因为是全局调用,所以我们要在方法前加上synchronized方法,来保证线程安全。这对于我们使用单例模式十分重要。一但我们获得该类的实例,就有可能有多个线程同使用它。但是如果我们要使用它,我们就要在活动中的创建资源时初始化该方法,并获得该方法的实例。

public void onCreateResources( onCreateResourcesCallback pOnCreateResourceCallback){

ResourceManager.getInstance().loadGameTexture(mEngine,this);

ResourceManager.getInstance().loadFonts(mEngine);

ResourceManager.getInstance().loadSounds(mEngine,this);

pOnCreateResourceCallBback.oncreateResourceFinished();

在第一步中,我们声明了所有的资源,包括字体Font对象,ITextureRgeioncfqj和声音、音效对象。但我们仅在DEMO中使用较少的资源,如果对于完整的游戏,我们可能有50、75甚至更多的资源,为了从SourceManager中获取这些对象,我们可以通过以下方法解决:

ResourceManager.getInstance().mGameBackgroundTextureRegion;

第二步,我实现loadGameTextures(pEngine,pContext)方法,用来加载游戏场景图片,对于每一个独立的场景我们都要为其实现一个load方法。

最后,我们相对于load方法要实现unload()方法,用来回收不用的资源。如果寻于那些在整个游戏中都要使用的资源图片,也可以不用伴随实现unload方法。


在比较大型的项目中,有时我们会发现 ,很多主要的对象使用比较频繁,所以另一种ResourceManager用途是存储常用的对象,比如Engine、Camera等在整个项目中都要调用的,通过参数传递,而不是通过get方法。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值