Command Design Pattern in Unity
The command pattern is a behavioral pattern that allows you to record the actions or events of your application. A good example of this is in tactical games when a player can plan out multiple moves for multiple characters and then play them out and rewind if they are bad moves.
To set up an example of the command pattern I have set up a simple scene with three cubes and some buttons.
The first thing to do is to create an interface that will have an execute and an undue method.
Next, create a simple user input script that will allow the player to click. This will create a raycast when the player clicks if the cubes are detected a new ICommand will be created. It will then call the execute method. It will lastly add the new ICommand to a list using a method in a simple command manager script.
Create a script for the click command that will inherit ICommand. This script will have references to a cube game object, a color, and a previous color.
The execute method will set the previous color to the current color and then change the color of the cube.
The undue method will set the color of the cube to the previous color.
Now it is time to talk about the command manager script.
First, make this script a singleton.
Create a list that will hold the ICommands.
You will create a method to add a command to the list.
A play method that will call a coroutine that will call the execute method on each command.
A rewind method that will do what the play method does but will go through the list backward and call the undue method.
A done method that will turn all the cubes to white.
And a reset method that will clear the list.
Now go into unity and set the buttons to call the right methods for the buttons being clicked and you will be able to record a sequence of clicks and play it forward or in reverse.