Course contentsShow
← Unity Game Development
Lesson 442 of 8287. Advanced Game ArchitectureFree lesson

Reducing Object Coupling with Command Pattern Architectures

You will implement the command pattern to decouple the invoker of an action from the object that actually performs the game logic.

In this lesson, you will learn how to decouple the source of a game action from the logic that executes it by wrapping requests into standalone objects.

The Problem: Tight Coupling

In many Unity projects, an InputHandler might directly reference a Player script: player.Jump(). While simple, this creates a hard dependency. If you want the AI or a UI button to trigger that jump, you have to keep rewriting or linking that logic. If the Player script changes, your InputHandler breaks.

The Solution: The Command Pattern

The Command Pattern moves the action into its own class. Instead of the InputHandler knowing how to jump, it simply holds a reference to an ICommand interface. The InputHandler says "Execute," and the command object handles the rest.

First, define your interface:

public interface ICommand {
    void Execute();
}

Next, create a concrete command that knows who to talk to:

public class JumpCommand : ICommand {
    private Player _player;
    public JumpCommand(Player player) => _player = player;

    public void Execute() => _player.Jump();
}

Now, your InputHandler doesn't need to know about the Player class at all; it only needs an ICommand. You can swap JumpCommand for AttackCommand or CrouchCommand at runtime without ever touching the InputHandler code.

Decoupling Benefits

By abstracting the request, you gain two major architectural advantages:

  1. Flexibility: You can queue commands, undo them, or trigger them from any system (UI, AI, or Input) without adding references to the underlying game logic.
  2. Maintenance: You adhere to the Single Responsibility Principle. The InputHandler is only responsible for detecting input, while the Command objects are responsible for the execution logic. Your systems become plug-and-play modules rather than a tangled web of direct object references.

Key Takeaway: The Command Pattern turns method calls into objects, allowing you to trigger game logic from any system without requiring the invoker to know anything about the receiver.