Reputation: 57
I am making a game in Kotlin.Using Libgdx and Box2d
1.function creates bodies via Box2d and adds these bodies in bodyArrayList:ArrayList
2.function creates textures and adds these textures in textureArrayList
3.function is matching items of bodyArrayList with items of textureArrayList. The function has for loop.
4.function is removing bodies when crash a wall.
5.function is removing textures when crash a wall.
All functions are working in update() method. All these are working perfectly. However because I cannot remove items of te ArrayLists while for loop works on these ArrayLists, items of ArrayList is increasing and the game is starting slowing downn 1 hour later. The ArrayLists' size is going up as you guess. If I try to remove items of ArrayLists I am taking exceptions in matching() function as you guess.
My question is how can I remove these items from ArrayLists while "for loop" is working in a safe manner.
1.function creates bodies
var body = makeBody()
bodyArray.add(body)
2.function creates textures
var texture=makeTexture()
textureArray.add(texture)
3.function is matching items of bodyArrayList with items of textureArrayList
for (i in 0..bodyArray.size-1) {
textureArray[i].setPosition(bodyArray[i].position.x, bodyArray[i].position.y)
}
4.funtion is removing bodies when crash a wall.
override fun beginContact(contact: Contact?) {
val userDataA = contact!!.fixtureA.userData.toString()
val userDataB = contact.fixtureB.userData.toString()
if ((userDataA == "ball" && userDataB == "wall")){
val bodyA=contact.fixtureA.body
Gdx.app.postRunnable(Runnable(){
run(){
world.destroyBody(bodyA) } })
}
5.function is removing textures when crash a wall.
for (texture: MyTextures in MyTextures.getList(Ball::class.java.canonicalName)) {
if (ball.overlaps(wall)) {
ball.remove() }
}
Upvotes: 2
Views: 1677
Reputation: 423
if you are using badLogic Array class
you can give your texture class to it and dispose every item of it in dispose method
private val texture = Texture("badlogic.jpg")
private val myArray = Array<Texture>()
fun dispose(){
myArray[i].dispose()
}
this is the link for more info on textures...
also you can dispose Screen
Class
Upvotes: 0
Reputation: 12953
You can use Iterator
to remove items from Collections
while iterating
val list = arrayListOf<Int>()
val listIterator = list.iterator()
while(listIterator.hasNext()){
//get item
val item = listIterator.next()
//items can be removed safely using
listIterator.remove()
}
Upvotes: 1