Click or drag to resize

SimpleStateMachineT Constructor

Constructs a new uninitialized state machine.

Namespace:  KSPDev.ProcessingUtils
Assembly:  KSPDev_Utils.2.5 (in KSPDev_Utils.2.5.dll) Version: 2.5 for KSP v1
Syntax
C#
public SimpleStateMachine(
	bool strict = true
)
Request Example View Source

Parameters

strict (Optional)
Type: SystemBoolean
Tells if all the transitions must be explicitly declared.
Examples
class SimpleStateMachineStrict {
  public enum State {
    One,
    Two,
    Three
  };

  public void TestMachine() {
    var sm = new SimpleStateMachine<State>(strict: true);
    sm.SetTransitionConstraint(State.One, new State[] { State.Two });
    sm.AddStateHandlers(
        State.One,
        enterHandler: newState => LogFromTo(sm.currentState, newState),
        leaveHandler: newState => LogFromTo(sm.currentState, newState));

    sm.currentState = State.One;  // Start the machine.
    // Logs: Move from NULL to One

    if (sm.CheckCanSwitchTo(State.Two)) {
      sm.currentState = State.Two;  // An allowed tranistion.
      // Logs: Move from One to Two
    }

    if (sm.CheckCanSwitchTo(State.Three)) {
      // This will never happen.
      sm.currentState = State.Three;
    }

    sm.currentState = null;  // Stop the machine.
    // Logs: Move Two to NULL
  }

  void LogFromTo(State? from, State? to) {
    Debug.LogFormat(
        "Move from {0} to {1}", DbgFormatter.Nullable(from), DbgFormatter.Nullable(to));
  }
}
Examples
class SimpleStateMachineFree {
  public enum State {
    One,
    Two,
    Three
  };

  public void TestMachine() {
    var sm = new SimpleStateMachine<State>(strict: false);
    sm.AddStateHandlers(
        State.One,
        enterHandler: oldState => Debug.Log("Now in state ONE"),
        leaveHandler: newState => Debug.LogFormat("Going into state: {0}", newState));
    sm.onBeforeTransition += (from, to) => Debug.LogFormat(
        "Before move: current={0}, new={1}",
        DbgFormatter.Nullable(sm.currentState), DbgFormatter.Nullable(to));
    sm.onAfterTransition += (from, to) => Debug.LogFormat(
        "After move: old={0}, current={1}",
        DbgFormatter.Nullable(from), DbgFormatter.Nullable(sm.currentState));

    sm.currentState = State.One;  // Start the machine.
    // Logs:
    // Now in state ONE
    // Before move: current=NULL, new=One
    // After move: old=NULL, current=One

    sm.currentState = State.Two;
    // Logs:
    // Going into state: Two
    // Before move: current=One, new=Two
    // After move: old=One, current=Two

    sm.currentState = State.Three;
    // Logs:
    // Before move: current=Two, new=Three
    // After move: old=Two, current=Three

    sm.currentState = null;  // Stop the machine.
    // Logs:
    // Before move: current=Three, new=NULL
    // After move: old=Three, current=NULL
  }
}
See Also