GKState:为什么 self.stateMachine == nil?
GKState: Why is self.stateMachine == nil?
我的 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()
输出为"No StateMachine"。
我想知道为什么 MyState 的 StateMachine 属性 是 nil?
因为你打错了:
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()
我的 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()
输出为"No StateMachine"。 我想知道为什么 MyState 的 StateMachine 属性 是 nil?
因为你打错了:
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()