Posted on 21 May 2014

Breakout clone in Unity


No I am not talking about the Swing Out Sister song! It's been a little while since I worked in Unity®, so earlier this week I decided to create a Breakout clone using it! I had started on something similar many months ago when I was first introduced to Unity, however some things came up and I never got it beyond the initial "the ball bounces and breaks bricks" stage. I didn't use any of that previous code/project as the point of this was to get familiar with the Unity toolset again.

This post isn't going to be a complete walk-through of the code like my others usually are. However I would like to point out that in the creation of this game I utilized the things I went over in my previous finite state machine framework and unity compatible singleton posts. Feel free to take a look at those to get a good idea of how/why some things in the code are done the way that they are. Here are some gameplay and technical details on the game:

  • Single player
  • Tracks high score
  • Sound effects
  • Uses a FSM to organize and control the flow of the game.
  • Limit the game to a 16:9 aspect ratio
  • Controls to move paddle are 'a' or 'left' to move left, and 'd' or 'right' to move right.

The sound effects and button skin are all free from the asset store. I used some sounds effects from 8 Bit Retro Rampage: Free Edition and a button skin from Extra GUI Skins.

One snippet of code I will show and explain a little bit is the method for generating the stages.

public void GenerateLevel(int rows, int columns) {
    for(int r = 0; r < rows; ++r) {
        for(int c = 0; c < columns; ++c) {
            // Create brick from prefab.
            GameObject tmp = Instantiate(brick, transform.position, Quaternion.identity) as GameObject;
            // Set parent to gameObject.transform so it is nested under it in the hierarchy.
            tmp.transform.parent = transform;
            // Set the local position(in relation to parent) according to it's row and column.
            tmp.transform.localPosition = new Vector3(c * .96f, r * -0.25f, 0f);
            // Determine which color this brick should be.
            switch(Random.Range(0, 3)) {
                case 0:
                case 1:


Much of that is pretty straightforward, but take a look at the line tmp.transform.localPosition = new Vector3(c * .96f, r * -0.25f, 0f);. The coefficients you multiply there depend on the size of the bricks you have, and how much you'd like them to be spaced apart horizontally and vertically. The switch statement is just to add some variety to the stages each time you play. There are numerous ways that this could be taken a step further such as by deciding on a way to limit various block types based on the stage the player is on.

As always, you can check out the repository for this project here, and it is also listed on my projects page. Additionally if you just want to check out the game you can download the zip here.