【问题标题】:Memory increase when returning to GameScene返回 GameScene 时内存增加
【发布时间】:2019-08-27 19:40:23
【问题描述】:

我正在创建一个包含多个场景的游戏,但我的问题在于游戏场景。当我开始玩然后返回菜单场景时,我注意到内存没有被释放,而是每次我进入游戏场景时内存都在不断增加,最终崩溃。

我已经尝试在函数“willMove”中从 self 中删除所有动作和子项,如下所示:

override func willMove(from view: SKView) {
        self.removeAllActions()
        self.removeAllChildren()
    }

但它什么也没做。

我认为我的问题是我有太多这样的 SKAction 动画:

//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 的新手,很抱歉。非常感谢任何帮助。

【问题讨论】:

  • 你们有闭包吗?
  • 更好的是你能显示整个游戏场景文件吗?
  • 尝试删除在willMove中重复(永远)的节点的所有操作。
  • @LucaAngeletti 谢谢!!

标签: ios swift xcode sprite-kit


【解决方案1】:

实际上很难为您提供一个无法与您一起调试并查看您如何管理游戏中的引用的解决方案,但我已经遇到了这个问题并且我能够使用以下两件事来解决它:


deinit {
    print("(Name of the SKNode) deinit")
}

使用它,我可以找到弧无法删除引用的对象。


 let color4 = SKAction.run { [weak self] in
     self?.label.fontColor = .green
 }

这个帮助我清理了我的游戏中的所有强引用。对于我们中的许多人来说,最好的做法是始终使用弱结合 self 内部闭包来避免保留循环。但是,只有当 self 也保留闭包时才需要这样做。 More Information.


【讨论】:

  • 谢谢!我的 SKActions 是问题的根源,让 [weak self] 解决了它。
  • 如果您能选择我的答案作为正确答案,我将不胜感激!谢谢,@EFS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多