A Unity example demonstrating the Chain of Responsibility pattern with a game input handling system.
The Chain of Responsibility pattern manages input handling across different game states (gameplay, UI, cutscenes, dialog). Each handler processes input based on the current game state, ensuring inputs are handled appropriately in each context.
InputState.cs
: Defines the possible game statesInputData.cs
: Contains all input information (movement, buttons)InputHandler.cs
: Base handler class with chain logic- Game States:
GameplayInputHandler.cs
: Handles player movement and actionsUIInputHandler.cs
: Handles UI navigation and selectionCutsceneInputHandler.cs
: Handles cutscene controlsDialogInputHandler.cs
: Handles dialog system input
InputManager.cs
: Sets up the chain and manages game states
// Setup is automatic - just add to a GameObject
InputManager manager = gameObject.AddComponent<InputManager>();
// Change states as needed
manager.SetGameState(InputState.Dialog); // When entering dialog
manager.SetGameState(InputState.Gameplay); // When returning to gameplay
- Clean separation of input handling by game state
- Easy to add new input states and handlers
- Prevents input conflicts between states
- Centralized input management