我正在创建一个包含多个场景的游戏,但我的问题出在游戏场景中。当我开始玩然后返回到菜单场景时,我注意到内存没有被释放,而是每次我进入游戏场景时内存都在不断增加,最终它崩溃了。
我已经尝试在函数“willMove”中删除 self 的所有 Action 和子项,如下所示:
override func willMove(from view: SKView) {
self.removeAllActions()
self.removeAllChildren()
}
但它什么也没做。
我相信我的问题是我有太多像这样的 SKActions 制作的动画:
//example 1, whiteCircle is an SKShapeNode
whiteCircle.run(.sequence([.scale(to: 1.5, duration: 0.5), .removeFromParent()]))
//example 2, SKAction.colorize doesn't work with SKLabels so I did this
let color1 = SKAction.run {
label.fontColor = .red
}
let color2 = SKAction.run {
label.fontColor = .yellow
}
let color3 = SKAction.run {
label.fontColor = .blue
}
let color4 = SKAction.run {
label.fontColor = .green
}
let wait = SKAction.wait(forDuration: 0.2)
label.run(SKAction.repeatForever(SKAction.sequence([color1, wait, color2, wait, color3, wait, color4, wait])))
//example 3, this is to refresh the label's text and change it's color
coinLabel.run(SKAction.sequence([.wait(forDuration: 3.25), .run {
self.coinLabel.fontColor = .yellow
self.coinLabel.text = "\(UserDefaults.standard.integer(forKey: "coins"))"
}]))
我也使用了很多图像作为 SKTextures,像这样使用:
coinIcon.texture = SKTexture(image: UIImage(named: "coinImage")!)
我的变量在GameScene类中都是这样声明的:
var ground = SKSpriteNode()
var ceiling = SKSpriteNode()
var character = SKSpriteNode()
var scoreLabel = SKLabelNode()
var coinLabel = SKLabelNode()
var coinIcon = SKLabelNode()
我想我可能正在创建一个强大的引用循环,但我不知道在哪里或如何识别它,我是 SpriteKit 的新手,如果我的问题看起来很愚蠢,我很抱歉。非常感谢任何帮助。
最佳答案
很难真正为您提供无法与您一起调试并查看您如何管理游戏中的引用的解决方案,但我已经遇到了这个问题,并且我能够使用这两个东西解决它:
deinit {
print("(Name of the SKNode) deinit")
}
使用它,我可以找到弧无法删除引用的对象。
let color4 = SKAction.run { [weak self] in
self?.label.fontColor = .green
}
这个帮助我清理了游戏中的所有强引用。对于我们中的许多人来说,最好的做法是始终在闭包内部使用 weak 结合 self 来避免保留循环。但是,只有在 self 也保留闭包时才需要这样做。 More Information.
关于ios - 返回 GameScene 时内存增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681251/