Command Pattern in Unity

Command Pattern in Unity

Hi, In this article I will explain how I used the command pattern in my mobile game Color Blocks.

As a beginning, I want to clarify why I used command pattern and how I used it. In my game, the player has to fill empty places with dragging blocks to left, right etc. Each movement of blocks is a command and the player should be able to take back commands. For taking back, all blocks have to be stored.

Command Pattern's help is that all commands in Command Pattern are objects so we can store our command and call them when we need. All we need to do this is creating a new instance of a command with arguments and execute it.

We start with creating an ICommand interface. We will implement this interface to our commands.

carbon.png

ICommand interface has Execute and Undo methods with void types. Process what our command do will be happen under the Execute method. Inverse of the process will be happen under the Undo method.

After the implementing ICommand interface to our MoveLeftCommand, it will look like below.

carbon (2).png

We get necessary parameters from the command's constructer.

In conclusion, we create a CommandManager for managing commands. Our manager class has a stack with ICommand type for storing commands.

Also, it has AddCommand and UndoCommand methods for adding commands to stack and revoke our last command.

carbon (3).png

In our app, we create a command object and add it to the stack with AddCommand. We call our command with command.Execute(). If we want to revoke our movement, we call UndoCommmand.

carbon (4).png

Result:

undo.gif

Source: https://learn.unity.com

Game: Color Blocks

Website|LinkedIn|GitHub|Twitter