Search code examples
swiftgameplay-kit

GKState: Why is self.stateMachine == nil?


I have following Code in my Playground:

import GameplayKit
class TestClass {
    var sm: GKStateMachine

    init() {
        sm = GKStateMachine(states: [MyState()])
        sm.enter(MyState.self)
    }
}

class MyState: GKState {

    override init() {
        super.init()
    }
    override func didEnter(from previousState: GKState?) {
        printStateM()
    }
    func printStateM() {
        if (self.stateMachine == nil) {
            print("StateMachine")
        } else {
            print("No StateMachine")
        }
    }
}

var t = TestClass()

The output is "No StateMachine". I wonder why the StateMachine Property of MyState is nil?


Solution

  • Because you made a typo:

    import GameplayKit
    class TestClass {
        var sm: GKStateMachine
    
        init() {
            sm = GKStateMachine(states: [MyState()])
            sm.enter(MyState.self)
        }
    }
    
    class MyState: GKState {
    
        override init() {
            super.init()
        }
        override func didEnter(from previousState: GKState?) {
            printStateM()
        }
        func printStateM() {
            if (self.stateMachine != nil) { // ⚠️
                print("StateMachine")
            } else {
                print("No StateMachine")
            }
        }
    }
    
    var t = TestClass()
    

    better yet, you can actually print it:

    import GameplayKit
    class TestClass {
        var sm: GKStateMachine
    
        init() {
            sm = GKStateMachine(states: [MyState()])
            sm.enter(MyState.self)
        }
    }
    
    class MyState: GKState {
    
        override init() {
            super.init()
        }
    
        override func didEnter(from previousState: GKState?) {
            printStateM()
        }
    
        func printStateM() {
            if let stateMachine = self.stateMachine {
                print("StateMachine: \(stateMachine)")
            } else {
                print("No StateMachine")
            }
        }
    }
    
    var t = TestClass()