The Command pattern in Unity
Objective: Show a way to use the command pattern in Unity
In object-orientated programming the command pattern is a design pattern which encapsulates all the information needed to perform an action at a later time. This saves on unnecessary update calls.
In this example I will be showing how to use the command pattern to play animations through the handler.
First I created an abstract class in Unity called Command.cs I then removed the monobehaviour from the class.
I am passing in the animator component of the gameobject that I would like to manipulate.
The next thing to do is to create come other classes that will override the Command class and Execute what I want.
All of the above classes are inside the Command.cs file. They’re their own classes but they all inherit from Command. That is the setup for that script. Now to assign these commands in the inputHandler.
I have created a new script called InputHandler.cs and attached this to an empty gameobject in the scene called, you guessed it ‘InputHandler’.
For the inputHandler I need access to a few things. I need a gameobject that I can change the animations of, I also need the animator of that object. I need a few references to the Command script for my various commands and then I have made some keycodes available to any designers that need to change the keys to play the animations.
Now in the start method I need to assign the animator, and the 3 commands I have.
I set the commands to their relevant methods that I want them to execute and I get the animator that is attached to the _actor.
Now, instead of hardcoding the keys that need to be pressed to execute the commands, I have set it up so that any designers can change the keys at any time in the editor without having to make any code changes.
And that is it for the basic set up for a command design pattern. Come back for more on design patterns.