ios – 从记忆中免费获得SKTextureAtlas

我有一个问题,让纹理图集自由.目前我有一个SpriteKit游戏,玩家可以改变他的角色.现在我在全球共享实例中有这样的地图册.

let char0Atlas: SKTextureAtlas = SKTextureAtlas(named: "Atlas/iPhone/char0")
let char1Atlas: SKTextureAtlas = SKTextureAtlas(named: "Atlas/iPhone/char1")
let char2Atlas: SKTextureAtlas = SKTextureAtlas(named: "Atlas/iPhone/char2")

您可以更改的每个角色都有自己的纹理图集.我用这样的方法获取玩家移动,空闲,并从该角色地图集中跳转动画:

func charAnimation(char: CharEnum) -> [SKTexture] {
    var temp: [SKTexture] = []
    var name: String = ""

    let atlas: SKTextureAtlas = char.atlasForChar()

    for i in 1...20 {
        if i > 9 { name = "char_\(charId)_idle_00\(i)" }
        else { name = "char_\(charId)_idle_000\(i)" }
        temp.append(atlas.textureNamed(name))
    }

    return temp
}

并且它存储在播放器精灵节点类的数组实例变量中.因此,每次更改一个字符时,这些帧都会被新帧替换,因此旧的帧应该被正确释放?

class PlayerNode: SpriteNode {
    private var currentAnimation: [SKTexture] = []
    private var animations: (idle: [SKTexture], run: [SKTexture], jump: [SKTexture]) = PlayerController.animationsForHero(.CharOne)
}

此外,当播放器切换字符时,我使用它来预加载纹理图集:

SKTextureAtlas.preloadTextureAtlases([char.atlasForHero()], withCompletionHandler: { () -> Void in
            updateChar()
        })

为什么SpriteKit永远不会从以前的角色动画中释放内存?如果播放器切换到新角色,则内存会不断增加并使应用崩溃.如果再次选择已在该会话中选择的角色,则内存不会增加.这表明内存泄漏.角色动画未被释放.为什么?

我知道SpriteKit应该自己处理这些东西,所以这就是它令人困惑的原因.绝对没有办法手动释放纹理图集吗?

谢谢!

最佳答案 @dragoneye第一点是正确的:你必须只预加载一次SKTextureAtlas.

看看Apple的文档Working with Sprites

>将纹理预加载到内存中
>从内存中删除纹理

然后,如果没有释放内存,这可能是因为仍存在对第二点所指向的SKTexture的引用:

After a texture is loaded into the graphics hardware’s memory, it stays in memory until the referencing SKTexture object is deleted. This means that between levels (or in a dynamic game), you may need to make sure a texture object is deleted. Delete a SKTexture object object by removing any strong references to it, including:

  • All texture references from SKSpriteNode and SKEffectNode objects in your game
  • Any strong references to the texture in your own code
  • An SKTextureAtlas object that was used to create the texture object
点赞