Unity: Create a Simple Board Game
Difficulty: ★★☆☆☆
Supported Unity version: Unity 2018.2 or higher
Introduction
It’s not difficult to make a simple board game that rolls a dice and move forward. Here is how to do so.
Prerequisites
- Basic knowledge of Unity C# programming
Steps
Step 1: Create a 3D Project
Creating a 2D project is also fine, but it is easier to illustrate the idea in 3D.
Step 2: Create the first step using a 3D Cube
Add a cube by selecting Unity menu > Game Object > 3D Object > Cube, and resize it to X = 1, Y = 0.1, Z = 1, and reset the position to X = 0, Y = 0, Z = 0 (also known as the origin).
Create a new Material, and change the colour to any colour you like. Create a material using Unity menu > Assets > Create > Material. Name it as “Step Material”. In the Inspector panel, change the colour at the Albedo settings.
Drag the newly created material to the cube you created earlier to change the cube’s colour.
Before we copy the cube to form more steps, let’s make it a Prefab. Prefab is the game object template in Unity. Once you created the Prefab, you can create as many copies as you want.
First, we rename the cube as “Step” in the Hierarchy panel. Then, we create a folder named “Prefab” in the Project panel. Then, we drag the “Step” game object from the Hierarchy window to the Prefab folder. If successful, the icon of the “Step” game object will become blue colour, which represents the Game Object is a Prefab.
The advantage of Prefab is that we can change the settings in the Prefab (e.g. change the colour or size), all instances of that Prefab in the scene will change at the same time.
Step 3: Build the steps
Create an empty game object, and rename it as “Steps”. Drag the Step game object into the “Steps” game object as a child object.
The following step is quite straightforward. Just duplicate the steps and form a straight line. I recommend you to leave some space between the steps in order to let players count the steps easily.
For example, the first step is located at X = 0, the second step will be located at X = -1.1.
Let’s build 20 steps.
Note: it’s a good practice to rename the steps into a meaningful name.
Step 4: Create our character
Let’s create a capsule as our character. You can use any 3D shape as well. Create a 3D Capsule via Unity menu > GameObject > 3D Object > Capsule. Move and scale the Capsule to position X = 0, Y = 0.5, Z = 0 and scale X,Y,Z = 0.5. Rename it to “Character”.
Step 5: Add the Roll Dice User Interface button
Next, we will add a Roll Dice button in the User Interface. To add a button, go to Unity menu > GameObject > UI > Button. In the Hierarchy panel, there will be three items added: EventSystem, Canvas and Button (with a Text game object as child).
Select Canvas, in the Inspector panel, change the Render Mode of the Canvas to “Screen Space — Camera” and select the Main Camera as the render camera.
Change the position of the button to the lower right corner. For your reference, I set it to X = -875, Y = -460 and width & height set to 120 units.
It’s better to show an image instead of the button text. I have prepared some dice images for you (which can be downloaded here):
Create a new folder in the Project panel named “Dice images”, and drag the images into the newly created folder. If you select one of the images in the Project panel, you will see that the Texture Type shown in the Inspector Panel is set to “Sprite (2D and UI)”. If not, set to this value and click Apply for all dice images. For all dice images, set Pixels Per Unit to 500
; click Apply.
To apply an image to the button, first, remove the Text game object under the Button game object. Then, drag the “dice0” image to the Source Image property and set Image Type to “Single”. Then, click the Set Native Size button.
Optionally, create a UI Text above the button and change the text to “Roll Dice”.
Step 6: Writes code to roll a dice
Now it’s the scary part for some of you. We are going to create a C# script in the Main Camera, named GameSceneController. Double click the script to launch Visual Studio code editor. At the beginning it looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GameSceneController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
} // Update is called once per frame
void Update()
{
}
}
We first add a button click function named RollDice()
before the last closing curly bracket:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GameSceneController : MonoBehaviour
{ private float stepX; // Start is called before the first frame update
void Start()
{
stepX = 0;
} // Update is called once per frame
void Update()
{
} public void RollDice()
{
int result = Random.Range(1, 6);
Debug.Log("Dice rolled: " + result);
stepX += 1.1f * result;
}
}
The bold parts are new.
Explanation: Once we clicked the Roll Dice button, the function RollDice()
will be called. A random number 1 to 6 will be selected, simulating the dice rolling action. Then, in the Debug.Log()
line, we will show the rolled dice number in the Debug Console in the Unity editor. Last, we will add the value named stepX
by 1.1 unit times the rolled dice number. The reason for using 1.1 is that our steps are separated by 0.1 unit and the width of each step is 1.0 unit (1.0 + 0.1 = 1.1).
float
data type in C# means small numbers with decimal places.
We’re not done with scripting yet. So far we just set a value name stepX
but our character hasn’t told to move yet. That’s what we’re going to do.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GameSceneController : MonoBehaviour
{ public GameObject character;
private float stepX;
private int speed = 3; // Start is called before the first frame update
void Start()
{
stepX = 0;
} // Update is called once per frame
void Update()
{
Vector3 target = character.transform.position;
target.x = stepX;
character.transform.position = Vector3.MoveTowards(character.transform.position, target, Time.deltaTime * speed);
} public void RollDice()
{
int result = Random.Range(1, 6);
Debug.Log("Dice rolled: " + result);
stepX += 1.1f * result;
}
}
We further add a few lines (highlighted in bold) to instruct the character to move according to the value of stepX
.
Explanation: We first add a reference (linkage) of our game character using a public GameObject
named character
, then we set a speed of value equals to 3
(you can adjust the value, of course). Then, in the Update()
function (which is executed every frame; if your game is running at 30FPS, this function will run 30 times per second), we added a few lines of codes, which:
- obtains the position of the character,
- change the X position to the value of
stepX
- Use the
Vector3.MoveTowards()
function to change the character position smoothly.
The basic script is complete (see? it’s super simple!). Let’s go back to our Unity editor.
Step 7: Links things up
Button Action
Select the button under the Canvas. In the Inspector panel, find the On Click section (around the bottom). Click the + button, under the Runtime Only drop-down menu you will find an object selection box, select Scene >Main Camera (or you can drag the Main Camera from the Hierarchy panel to the box). Then, in the drop-down box on the right, select GameSceneController > RollDice().
Character in Script
Select the Main Camera, in the Inspector panel, find the Game Scene Controller script settings. Drag the Capsule game object from the Hierarchy panel to the Character object selection box.
Step 8: Adjust Camera angle
The default camera angle can only view the side view of the steps and the character, which is obviously not attractive at all.
My camera settings are:
Step 9: Test run the game
It’s time to test run the game. It looks fine, but when the character is moving along the steps, the camera does not follow. Stop the game.
It can easily be fixed by moving the Main Camera to be the child of the character so that the camera will follow the character wherever it goes.
Step 10: Extra Steps
The game is complete, but if you want to show the rolled dice as images (still remember we have some unused images?), you can adjust the script as follow:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class GameSceneController : MonoBehaviour
{
public GameObject character; public Sprite dice0;
public Sprite dice1;
public Sprite dice2;
public Sprite dice3;
public Sprite dice4;
public Sprite dice5;
public Sprite dice6;
public Button btnRollDice; private float stepX;
private int speed = 3; // Start is called before the first frame update
void Start()
{
stepX = 0;
} // Update is called once per frame
void Update()
{
Vector3 target = character.transform.position;
target.x = stepX;
character.transform.position = Vector3.MoveTowards(character.transform.position, target, Time.deltaTime * speed);
if(character.transform.position == target)
{
btnRollDice.GetComponent<Image>().sprite = dice0;
}
} public void RollDice()
{
int result = Random.Range(1, 6);
Debug.Log("Dice rolled: " + result);
stepX -= 1.1f * result; // Display sprite graphics
switch(result)
{
case 1:
btnRollDice.GetComponent<Image>().sprite = dice1;
break;
case 2:
btnRollDice.GetComponent<Image>().sprite = dice2;
break;
case 3:
btnRollDice.GetComponent<Image>().sprite = dice3;
break;
case 4:
btnRollDice.GetComponent<Image>().sprite = dice4;
break;
case 5:
btnRollDice.GetComponent<Image>().sprite = dice5;
break;
case 6:
btnRollDice.GetComponent<Image>().sprite = dice6;
break;
default:
btnRollDice.GetComponent<Image>().sprite = dice0;
break;
}
}
}
This time we added quite a lot of codes, but in fact, the logic is simple.
Explanation:
At the 4th line, we added a namespace called UnityEngine.UI
, which is a set of functions, objects and properties related to User Interface, as we have to use theButton
game object now.
Then we added a few public variables to link up assets and game objects with the script.
In the RollDice()
function, after randomly picked the result, the newly added logic displays the corresponding image in the button.
In the Update()
function, we check if the character has arrived at its destination. If yes, change the image back to the original image.
After adding these codes, save the changes and go back to our Unity Editor. In the Main Camera > Game Scene Controller script properties, drag the appropriate game objects and assets to the empty slots, as follow:
Save all the changes. Play the game. You will see the button image will change according to the rolled dice number.
That’s all steps for this simple game demo. I hope you enjoyed it.
If you encounter any questions, please leave a comment below. I’ll be happy to help.
Completed Project
The completed project can be downloaded here.