本文へスキップ
System Design

Beginner guide to state machines in game logic

Learn how to organize player, UI, dialogue, and progression logic around clear states before condition chains become hard to maintain.

公開日: 2026-06-26#StateMachine#Logic#Flow#Beginner

Quick Start

Start with a tiny working version

Game logic often becomes messy not because the game is already advanced, but because the project never clearly defined what state it is in. Idle, moving, attacking, paused, in dialogue, showing results, waiting for confirmation.

Build it in small code pieces

1. 値を用意する

Inspectorで変更できる値と表示先を置きます。

StateMachineTutorial.cs
csharp
    [SerializeField] private TextMeshProUGUI statusText;
    [SerializeField] private float stateIndex = 1f;
    [SerializeField] private float transitionCount = 2f;
    [SerializeField] private float stateSeconds = 3f;

2. 状態を変える

ボタンを押した時に、1つだけ状態を進めます。

StateMachineTutorial.cs
csharp
    public void NextStep()
    {
        step = (step + 1) % 3;
        var label = step == 0 ? "Idle" : step == 1 ? "Move" : "Attack";
        if (statusText != null)
        {
            statusText.text = $"{label}\nstateIndex={stateIndex:0.##}\ntransitionCount={transitionCount:0.##}\nstateSeconds={stateSeconds:0.##}";
        }

3. 画面に表示する

変わった結果を画面に出して確認します。

StateMachineTutorial.cs
csharp
        if (statusText != null)
        {
            statusText.text = $"{label}\nstateIndex={stateIndex:0.##}\ntransitionCount={transitionCount:0.##}\nstateSeconds={stateSeconds:0.##}";
        }
        Debug.Log($"ステートマシン: {label}");

Complete script

StateMachineTutorial.cs
csharp
using UnityEngine;
using TMPro;

public class StateMachineTutorial : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI statusText;
    [SerializeField] private float stateIndex = 1f;
    [SerializeField] private float transitionCount = 2f;
    [SerializeField] private float stateSeconds = 3f;

    private int step;

    public void NextStep()
    {
        step = (step + 1) % 3;
        var label = step == 0 ? "Idle" : step == 1 ? "Move" : "Attack";
        if (statusText != null)
        {
            statusText.text = $"{label}\nstateIndex={stateIndex:0.##}\ntransitionCount={transitionCount:0.##}\nstateSeconds={stateSeconds:0.##}";
        }
        Debug.Log($"ステートマシン: {label}");
    }
}

Inspector

Connect the UI reference in the Inspector, then use the button to confirm each value changes.

Summary

What to take away

Learn how to organize player, UI, dialogue, and progression logic around clear states before condition chains become hard to maintain.

The page is designed to help you move from reading to a small practical decision. Use the checklist above before jumping into the next related article.