AndEngine 删除精灵时报IndexOutOfBoundsException错误的解决方案

近期在使用Andengine框架写一个小游戏,在动态删除精灵时遇到了IndexOutOfBoundsException的问题,google了一下,在StackOverflow上找到了解决方案。

首先添加一个精灵的方法:

scene.attachChild(sprite);

 

删除一个精灵类的方法:

scene.detachChild(sprite);
sprite.dispose();
sprite= null;

 

IndexOutOfBoundsException原因是画面更新的线程会获取当前场景的所有元素实体,此时移除了精灵,又在画面更新线程中读到这个元素,导致索引越界了。移除精灵类则需要放在UIThread中执行,,如:

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {	  
scene.detachChild(sprite);
sprite.dispose();
sprite= null;
  
    }
});
 
参考:http://stackoverflow.com/questions/12540426/android-andengine-handling-collission-detection-properly
posted @ 2013-03-06 15:12  路人 乙  阅读(369)  评论(0编辑  收藏  举报