2014年2月14日 星期五

AndEngine Scene.detachChild(IEntity) exception : java.lang.IndexOutOfBoundsException 解決方法

事情是這樣的,用 AndEngine 開發遊戲的時候
想要移動一個 A 物件至 camera 外,並在移出後從 scene 刪掉

於是乎用了一個 MoveModifier 移動 A 物件的位置
並給了 Modifier 一個 IEntityModifierListener 並 override 了 onModifierFinished 這個方法
在這個方法中呼叫 Scene 的 detachChild() 來移除 A 物件

結果就出現例外了
FATAL EXCEPTION: UpdateThread
java.lang.IndexOutOfBoundsException: Invalid index 142, size is 142

google 了一下發現這是 thread 的 concurrency 問題
似乎是 Modifier 為另外的 thread 所操控
執行 detachChild() 時,須在 OnUpdate 的 thread 下執行

◎解決辦法
將 detachChild() 丟到以下位置即可

engine.runOnUpdateThread(new Runnable() {
@Override
public void run() {
scene.detachChild(entity);
}
});

Reference :
Exception while removing sprite from scene ( detachChild )

沒有留言:

張貼留言