我在获取免费的纹理图集时遇到问题。目前我有一个 SpriteKit 游戏,玩家可以在其中改变他的角色。现在我在这样的全局共享实例中拥有 map 集。
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
}
并且存储在玩家 Sprite 节点类的数组实例变量中。所以每次更改角色时,这些帧都会被新帧替换,所以旧帧应该被释放对吗?
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 从不释放以前角色动画的内存?如果玩家切换到新角色,内存会不断增加并导致应用程序崩溃。如果再次选择已在该 session 中选择的角色,则内存不会增加。这表明存在内存泄漏。角色动画没有被释放。为什么?
我知道 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 aSKTexture
object object by removing any strong references to it, including:
- All texture references from
SKSpriteNode
andSKEffectNode
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
关于ios - 从内存中释放 SKTextureAtlas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688604/