0

I'm using Gameplaykit's GKStateMachine to create a state machine for my game, but I run into an issue where I need to use the same variable inside multiple states. If I send them in with the init, then the variable will act independently of the original variable, which I find a bit strange to be honest because I assumed that reference variables always referenced its new value back to the original variable. But I guess it has to do with the fact that I store the value into a new variable.

class MyStateMachine: GKStateMachine {
    override init(states: [GKState]) {
        super.init(states: states)
    }
}

class MyState: GKState {
    var test: String
    
    init(test: String) {
        self.test = test
    }
    override func didEnter(from previousState: GKState?) {
        self.test = "State Value"
    }
}
var test = "Original Value"
var state = MyState(test: test)
var machine = MyStateMachine(states: [state])

machine.enter(MyState.self)

print(test) //Prints Original Value. Variable change in state does not reference back to original variable
print(state.test) //Prints State Value. State variable works independently of original value

Anyway, how do I use the same value across multiple state classes and have it always retain an updated value? That is, if I change the value of the variable in state1, that value needs to be reflected in state2 and so on.

First I thought about storing them inside the state machine itself. But creating instances of the state machine inside every state would create circle dependencies. Also a new instance would mean that the value of the state machine variable wasn't kept. So then I thought about Singeltons. Then the value would be retained over the entire app, so that would work. But it would mean that I would likely have to create about three different Singeltons. Perhaps that's fine, but I constantly hear people complain about the dangers of that pattern.

I'm not too familiar with the state machine pattern, so perhaps there's a simple built in solution to this that I simply don't know about.

Joakim Sjöstedt
  • 824
  • 2
  • 9
  • 18
  • The state has a reference to the state machine that contains it, so what difficulty could there be for different states to refer to values maintained by the machine? – matt May 03 '21 at 19:55
  • Nice, exactly what I want! How do I get ahold of the state machine from inside of the states? – Joakim Sjöstedt May 03 '21 at 19:57
  • 1
    https://developer.apple.com/documentation/gameplaykit/gkstate/1501041-statemachine – matt May 03 '21 at 19:57

0 Answers0