我在操场上有以下代码:
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()
输出为“ No StateMachine”。 我想知道为什么MyState的StateMachine属性为nil?
答案 0 :(得分:0)
因为您输入错误:
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()