简体   繁体   中英

Android Game - Screen Flickers When an Entity Removed From The List

I am using Canvas in my android game. When I remove a no longer displayed entity in my entity list, all other entities are flickering for a brief time. When it's not removed, there is no such problem. But since I am not a big fan of memory leaks, that's not an option.

The canvas rendering system is already double-buffered by design and I have utterly no idea how to fix such a problem. I have thought maybe it is because the list is sorting itself after the item removal and tried changing it to a Set, but that didn't work either.

Does anyone have any idea why this might be happening and how to fix it?

Structure of the code:

private val gameObjects: List<GameObject> = mutableListOf()
    
    fun update(deltaTime: Long)
    {
        gameObjects.forEach {
            it.update(deltaTime)
    }

 fun render(canvas: Canvas)
    {
      gameObjects.forEach {
         when (getVisibilityStatus(it.virtualY))
         {
            VisibilityStatus.VISIBLE -> it.render(canvas, virtualToPhysicalY(it.virtualY))

            VisibilityStatus.BELOW_SCREEN ->
            {
              if (virtualToPhysicalY(it.virtualY) > screenSizePairXY.second)
                gameObjects.remove(it)
            
            }
         }
    }

Removing elements from list you iterating its not safe practice. It would be better to do culling (removing invisible elements) before drawing cycle in separate cycle. Here is some explanation:

Remove elements from collection while iterating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM