State
What is it?
State is a behavioral design pattern that allows an object to change its behavior depending on its current internal state. In simple terms, the object stays the same, but it behaves differently in different situations.
In this pattern, each state is handled as a separate class. The main object, called the Context, keeps track of the active state and delegates the behavior to that state object. This avoids long if-else or switch-case blocks and creates a cleaner, more readable structure.
In Unity, the easiest example is character or enemy behavior. An enemy can have states such as Idle, Chase, Attack, and Escape. Instead of putting all of these behaviors into one large class, each behavior can be separated into its own state class.
This structure usually consists of three main parts: the main object that owns the state, a shared interface that all states follow, and concrete state classes that represent each behavior.
When is it used?
The State pattern is useful when an object's behavior changes frequently at runtime and these changes start creating complicated conditions in the code. It is especially helpful when the same object needs to act in completely different ways depending on its current mode.
In Unity, it is commonly used for:
- Enemy AI: idle, chase, attack, escape
- Character controllers: idle, running, jumping, attacking, taking damage
- Game flow: main menu, gameplay, pause, game over
- UI management: switching between menus, settings, loading screens, and gameplay screens
- Animation and interaction systems
However, it should not be used everywhere. If there are only two or three simple states, a bool, enum, or small conditional structure may be enough.
Animation
Code
namespace Patterns.Behavioral.State
{
public interface IState
{
void Enter();
void Tick();
void Exit();
}
}Advantages and Disadvantages
• Advantages:
- It makes the code more readable and easier to manage.
- New states can be added without changing existing state code.
- Each state can be tested more easily in isolation.
• Disadvantages:
- The number of classes can increase quickly.
- In small projects, it can feel unnecessarily complicated.
- Too much shared data can make the Context grow over time.
Tips
When using the State pattern in Unity, it is important to define the Enter, Update, and Exit methods clearly.
It is usually better to manage state transitions from a central structure such as the Context or a StateMachine.
When working with the Animator, using Animator.StringToHash() can be more efficient than repeating string parameters.
It is also a good idea to avoid creating new state objects every time a transition happens. Caching states can reduce garbage collection pressure.
ScriptableObject-based states can also be considered for more flexible systems.
Finally, if the number of states grows too much, a hierarchical state machine or a different AI structure may be more suitable.