CodeBlanks Logo Icon CodeBlanks

State machine

Learn enemy states with a simple FSM.

Finite State Machine (FSM)

An FSM (Finite State Machine) is a streamlined pattern ensuring a character resides in strictly one state at any given moment (e.g., Patrol, Chase, Attack).

public enum EnemyState {
    Patrol,
    Chase,
    Attack
}

States are modeled using an enum, preventing contradictory concurrent states.

State Transitions and the switch Statement

Every frame, behavior matching the active state executes within a switch-case block. When triggers fire, the state variable is updated.

switch (currentState) {
    case EnemyState.Patrol:
        PatrolAlongWaypoints();
        break;
    case EnemyState.Chase:
        agent.SetDestination(player.position);
        break;
}

For instance, when the player breaches proximity, setting currentState = EnemyState.Chase; launches pursuit.

Practice State machine transition

Define a Start method. Inside, declare string aktifDurum = "Chase"; and print "Dusman durumu: " + aktifDurum to the console.

Starter code

Player.cs
using UnityEngine;

public class FsmTester : MonoBehaviour
{
    // Start icinde aktifDurum tanimla ve yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class FsmTester : MonoBehaviour
{
    void Start()
    {
        string aktifDurum = "Chase";
        Debug.Log("Dusman durumu: " + aktifDurum);
    }
}

Expected output

Dusman durumu: Chase

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the architectural pattern called that transitions an enemy from Patrol to Chase upon spotting a player?

  • Finite State Machine (FSM) Correct answer
  • Audio Listener
  • Shader Pipeline
  • JSON Deserializer

Explanation: A Finite State Machine (FSM) manages transitions between discrete states based on sensory conditions.

2 Enemy states enum declaration

Question
public enum EnemyState { ____, Chase, Attack }
Answer
public enum EnemyState { Patrol, Chase, Attack }

Explanation: The 'Patrol' label is used to designate the default scouting state of an enemy.

3 FSM state concepts

Term Meaning
Patrol Patrolling along a predefined path
Chase Pursuing the player as a target
Attack Dealing damage when player is in range
FSM Machine selecting behavior by state

All lessons in Advanced