Game Design Pattern: Command Pt.1- Game Dev Series 136

S.J. Jason Liu
4 min readOct 11, 2021

Objective: using Command pattern to create a system would store process steps.

Here is another game design pattern called “Command”. Command design pattern would be handy when creating games like strategy and tactics games or turn-based strategy games. This pattern would be easy to record the steps of process and easy for user to rewind the passed precess.

Concept

In this tutorial, we would create a simple function with 3 cubes and an interface with 4 buttons.

What we are going to do is to change the color of cube randomly when clicking on it. Every time we clicked, the color would be store in a list. The 4 buttons would reveal 4 different functions:

  • Play button: replay the steps of what we click on cubes and change the color in order.
  • Rewind button: just like what Play button did but in backward.
  • Done button: recover all cubes into white and without adding any process to list.
  • Reset button: reset all process from list.

This might sound complicated and we will finish this step by step.

Environment

As the picture shows above, we need to create a game scene with 3 cubes and 4 buttons.

Once done, set a tag to those cubes.

With these objects done, we are ready to create the function.

Create ICommand & command class

First we need to create an interface of 2 needed methods: Execute & Undo, which is the key function that we use this design pattern.

Now we need to create a command class that implement this interface to handle the main function in this example: changing color.

Create PlayerInput

The next is to create a method that would recognize mouse click on those 3 cubes. We can create a new script and attach it to main camera.

When we click on cubes, we need to make sure that the function would only affect on cubes. Specified the cubes with tag to proceed the method.

Changing color

We will handle the color changing function in ClickCommand and this is also what we are going to store into list to playback later.
First we need to locate the clicked cube from PlayerInput, we can do this part by creating a constructor in ClickCommand. Inside constructor, we would need the game object and color to store in list. Let’s pass in these value.

And we also need some variables to store these value in script.

Then assign those pass in game object and color to these variables in constructor.

And now we can change the color in Execute().

For the Undo(), it would need to get the origin color before we changing it. We can do this by store the origin color in another variable.

Now we just need to call this script from PlayerInput.

Play and test it, you should see the color of cubes change when click on them.

In the next tutorial, we will continue create a system to store these command and replay it.

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.