1

I'm creating a game which consists of multiple scenes but my problem is in the game scene. When I start playing and then return to the menu scene I notice that memory isn't being freed, instead memory keeps increasing every time I go to the game scene and eventually it crashes.

I've already tried to remove all actions and children from self in the function 'willMove', like this:

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

But it did nothing.

I believe my problem is that I have too many animations made with SKActions like these:

//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"))"
            }]))

I'm using lots of images as SKTextures too, used like this:

    coinIcon.texture = SKTexture(image: UIImage(named: "coinImage")!)

My variables are all declared like this in the GameScene class:

    var ground = SKSpriteNode()
    var ceiling = SKSpriteNode()
    var character = SKSpriteNode()
    var scoreLabel = SKLabelNode()
    var coinLabel = SKLabelNode()
    var coinIcon = SKLabelNode()

I think I may be creating a strong reference cycle, but I don't know where or how to identify it, I'm new to SpriteKit so sorry if my question seems dumb. Any help is very much appreciated.

EFS
  • 85
  • 1
  • 5

1 Answers1

0

It's hard to actually give you a solution not being able to debug with you and see how you are managing references in your Game, but I've encoutered this issue and I was able to solve it using those two things:


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

Using this, I could find which objects the arc could not remove reference.


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

This one helped me clean all strong references in my Game. For many of us, it’s best practice to always use weak combined with self inside closures to avoid retain cycles. However, this is only needed if self also retains the closure. More Information.