Leaks using GKStateMachine in a Subclass

2019-06-01 01:05发布

I will show you my actual code. It has three elements: a Helper:

import SpriteKit
import GameplayKit

class GameSceneHelper: SKScene {

   override func didMove(to view: SKView) {

   }
}

A subclass of the helper with some game's states:

import SpriteKit
import GameplayKit

class GameScene: GameSceneHelper {

   lazy var gameState:GKStateMachine = GKStateMachine(states: [
      Introduction(scene: self),
      SecondState(scene: self) ])

   override func didMove(to view: SKView) {

      self.gameState.enter(Introduction.self)
   }
}

And the States. Here I present one of them. The other has the same structure:

import SpriteKit
import GameplayKit

class Introduction: GKState {

   weak var scene:GameScene?

   init(scene:SKScene) {
      self.scene = scene as? GameScene
      super.init()
   }

   override func didEnter(from previousState: GKState?) {
      print("INSIDE THE Introduction STATE")
   }
}

The problem is that I'm getting a Leak when I define the gameState variable inside the subclass of GameSceneHelper. But, If I don't use the subclass and instead I make the GameScene a direct subclass of SKScene, everything works. The problem is that for my project I need the helper so I can't take it out of the equation. Does anybody has any suggestion?

1条回答
贼婆χ
2楼-- · 2019-06-01 01:36

Ok. After a lot of time doing this I found the source of the problem. The declaration of the gameState must be moved from GameScene to GameSceneHelper like this:

class GameSceneHelper: SKScene {

   var gameState:GKStateMachine!

   override func didMove(to view: SKView) {
   }
}

No use for the lazy var declaration inside GameScene. Then everything works.

查看更多
登录 后发表回答