コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】シンプルなステートマシン「Unity3D - Simple Finite State Machine」紹介

はじめに

「Unity3D - Simple Finite State Machine」はシンプルなステートマシンです

使い方

using MonsterLove.StateMachine;

使用したいスクリプトに上記の using を追加します

public enum States
{
    Init, 
    Play, 
    Win, 
    Lose
}

ステートを表す列挙型を定義します

StateMachine<States> fsm;

StateMachine の変数を定義します

fsm = StateMachine<States>.Initialize(this);

StateMachine の変数を生成します

fsm.ChangeState(States.Init);

ステートを変更したい場合は ChangeState 関数を使用します

void Init_Enter()
{
    Debug.Log("We are now ready");
}

IEnumerator Play_Enter()
{
    Debug.Log("Game Starting in 3");
    yield return new WaitForSeconds(1);
    
    Debug.Log("Game Starting in 2");
    yield return new WaitForSeconds(1);
    
    Debug.Log("Game Starting in 1");
    yield return new WaitForSeconds(1);
    
    Debug.Log("Start"); 
}

void Play_Update()
{
    Debug.Log("Game Playing");
}

void Play_Exit()
{
    Debug.Log("Game Over");
}

各ステートで呼び出されるコールバックは上記のように記述します

関連記事