【问题标题】:GKState: Why is self.stateMachine == nil?GKState:为什么 self.stateMachine == nil?
【发布时间】:2019-04-18 23:02:42
【问题描述】:

我的 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()

输出是“无状态机”。 我想知道为什么 MyState 的 StateMachine 属性是 nil?

【问题讨论】:

  • 不应该是self.stateMachine != nil吗? (或者如果您打算使用该变量,您可能需要if let stateMachine = self.stateMachine 或类似的东西)

标签: swift gameplay-kit


【解决方案1】:

因为你打错了:

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()

更好的是,您可以实际打印它:

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()

【讨论】:

  • 我的印象是错字问题应该被关闭。
  • 是的,我提交了结束投票。不幸的是,我一个人做不到,需要另外 4 票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 2021-12-03
  • 2013-11-14
相关资源
最近更新 更多