# Command Pattern in Unity

Hi, In this article I will explain how I used the command pattern in my mobile game  [Color Blocks](https://play.google.com/store/apps/details?id=com.bariscanyilmaz.colorblocks).

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620059442543/TC0DIBbsB.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620060355143/Zmcelfnby.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620060640596/nsydVV2k-.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1620061959452/tmPqIfPeJ.png)

Result:

![undo.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1620062392665/pXQ1C-NcA.gif)
 

Source:
 [https://learn.unity.com](https://learn.unity.com) 

Game: [Color Blocks](https://play.google.com/store/apps/details?id=com.bariscanyilmaz.colorblocks)

[*Website*](http://bariscanyilmaz.com)|[*LinkedIn*](https://www.linkedin.com/in/bariscanyilmaz/)|[*GitHub*](https://github.com/bariscanyilmaz/)|[*Twitter*](https://twitter.com/1bariscanyilmaz)
