If logic in your controller to complex for ‘if’ or ‘switch\case’ constructions, here is small State Machine implementation for you.

Let’s start with example how to use this state machine, and then we go through implementation details:

public class Test : MonoBehaviour
{
    private StateMachine stateMachine;

    private State firstState = new State();
    private State secondState = new CustomState();
    private State finishState = new State();

    // Use this for initialization
    void Start ()
    {
        var initChild = new State()
            .AddStartAction(() => Debug.Log(Time.frameCount + " childInit Start"))
            .AddUpdateAction(() => Debug.Log(Time.frameCount + " childInit Update"))
            .AddStopAction(() => Debug.Log(Time.frameCount + " childInit Stop"));
        var childStateMachine = new StateMachine(initChild);
        stateMachine = new StateMachine(firstState);

        firstState
            .AddStartAction(() => Debug.Log(Time.frameCount + " 1 Start"))
            .AddUpdateAction(() => Debug.Log(Time.frameCount + " 1 Update"))
            .AddStopAction(() => Debug.Log(Time.frameCount + " 1 Stop"))
            .AddTransition(
                state => Time.frameCount == 5, 
                secondState)
            .AddTransition(
                state => Time.frameCount == 15,
                secondState);

        secondState
            .AddTransition(
                state => Time.frameCount == 10,
                firstState)
            .AddTransition(
                state => Input.GetKey(KeyCode.Q),
                childStateMachine);

        childStateMachine
            .AddTransition(s => Input.GetKey(KeyCode.Y), finishState);

        finishState
            .AddStartAction(() => Debug.Log(Time.frameCount + " finish Start"));

        stateMachine.Start();
    }

    void Update()
    {
        stateMachine.Update();
    }
}

public class CustomState : State
{
    public CustomState()
    {
        StartAction = CustomStart;
        UpdateAction = CustomUpdate;
        StopAction = CustomStop;
    }

    public void CustomStart()
    {
        Debug.Log(Time.frameCount + " custom start");
    }

    public void CustomUpdate()
    {
        Debug.Log(Time.frameCount + " custom update");
    }

    public void CustomStop()
    {
        Debug.Log(Time.frameCount + " custom stop");
    }
}

#c# #game dev #unity3d #programming-c

[Unity3d] Yet Another State Machine for Unity3d
1.40 GEEK