Ever wondered how the rewind/replay functionality works in games? The answer lies within the command pattern design system. Simply, the Command Pattern is a behavioral pattern that allows us to record the actions or events in our game, by isolating it from the game object.
To build a command pattern system, we of course need a behaviour (😮). An interface (usually named as ICommand) is created to determine the actions that will be used. Command script(s) will be created to construct new commands; which will be held in a data set in the Command Manager. By using the command manager, we will be able to achieve replay/rewind or any other functionality that we want to.
In the example below, we are going to build a prototype using the Command Pattern with ICommand Interface, by implementing Execute and Undo methods. For more details on interfaces, you can check my article on IDamageable interface by clicking here.
Here’s the scenario where we change the colors of the cubes by clicking on them. A command system will be built that will act upon the button clicks according to our past clicking actions on the cubes.
In the normal case, we would end up with a script as below (this is attached to main camera):
Using the command pattern, we isolate the behaviour (which is the changing color) from the game objects. Furthermore, it is easy enough to log the user input data.
First, create a new script for the interface.
For now, we will have 2 methods within the interface, Execute for changing the color and Undo for the reversing it.
Now, each time we click on a cube, we can call the Execute method from the UserClick script. However, to isolate the behaviour, we are going to use a Command Manager game object and script to handle the operations.
This is actually the first time I have ever included the Linq namespace in a project. In the RewindRoutine at the end of the script, we reverse the sorting of the list by using Enumerable.Reverse method, which belongs to System.Linq.
Lastly, to make sure that we add each click to the command list in the Command Manager, we need to call the method from the UserClick script. Thus, the UserClick script has been updated as below :
ICommand click = new ClickCommand(hitInfo.collider.gameObject, new Color(Random.value, Random.value, Random.value));
Now, the only thing to do is to assign the relevant methods to appropriate buttons and test it.