How to Create a Tower Defense Game in Unity – Part 1

In this tutorial, you’ll build a 2D tower defense game using the latest Unity engine. By Jeff Fisher.

Leave a rating/review
Save for later
Share
Update note: This tutorial has been updated to Unity 2017.1 by Jeff Fisher. The original tutorial was written by Barbara Reichart.

Tower defense games are incredibly popular, and no wonder — few things are more satisfying than watching your defense obliterate evil invaders! In this two-part tutorial, you build a tower defense game with Unity!

You’ll learn how to…

  • Create waves of enemies
  • Make them follow waypoints
  • Build and upgrade towers and let them reduce your enemies to pixels

At the end, you’ll have a framework for this genre that you can expand upon!

Note: You need to know Unity basics, like how to add game assets and components, understand prefabs and know some basic C#. To learn those things I recommend completing the Unity tutorials by Sean Duffy or the Beginning C# with Unity series by Brian Moakley.

I’m using the OS X version of Unity, but this tutorial works on Windows too.

A View from the Ivory Tower

In this tutorial, you build a tower defense game, where enemies — little bugs — crawl towards a cookie that belongs to you and your minions, which are of course monsters! You can place and upgrade monsters at strategic points for a bit of gold.

The player must kill the bugs before they feast on your cookie. Each wave of enemies is successively harder to defeat. The game ends when you survive all waves (Victory!) or when five enemies reach the cookie. (Defeat!).

Here’s a screenshot of the finished game:

Monsters Unite! Protect the cookie!

Monsters Unite! Protect your cookie!

Getting Started

If you don’t already have Unity installed, download it from Unity’s website.

Also, download this starter project, unzip and open the TowerDefense-Part1-Starter project in Unity.

The starter project includes art and sound assets, along with prebuilt animations and a few helpful scripts. The scripts aren’t directly related to tower defense games, so they won’t be explained here. However, if you’d like to learn more about creating Unity 2D animations, check out this Unity 2D tutorial.

The project also contains prefabs you’ll later expand upon to create characters. Finally, the project includes a scene with its background and user interface set up.

Open GameScene, found in the folder Scenes, and set your Game view’s aspect ratio to 4:3 to ensure the labels line up properly with the background. You should see the following in the Game view:

Starter Project Screenshot

Credits:

  • The art for the project comes from a free art pack by Vicki Wenderlich! You can find more awesome graphics from her at gameartguppy.
  • The cool music is from BenSound who has some great soundtracks!
  • Thanks goes to Michael Jasper for the impactful camera shake.

Starter project – check!
Assets – check!
The first step towards world domination… ehm, I mean your tower defense game…is done!

X Marks the Spot: Placement

Monsters can only post up at spots marked with an x.

To add these to the scene, drag and drop Images\Objects\Openspot from the Project Browser into the Scene view. For now, position doesn’t matter.

With Openspot selected in the Hierarchy, click Add Component in the Inspector and select Box Collider 2D. Unity displays the box collider with a green line in the Scene view. You’ll use this collider to detect mouse clicks on that spot.

Unity automatically detects the proper size for the collider. How cool is that?

Unity automatically detects the proper size for the collider. How cool is that?

Following the same steps, add an Audio\Audio Source component to Openspot. Set the Audio Source’s AudioClip to tower_place, which you can find in the Audio folder, and deactivate Play On Awake.

You need to create 11 more spots. While it’s tempting to repeat all those steps, Unity has a great solution for that: Prefabs!

Drag and drop Openspot from the Hierarchy into the Prefabs folder in the Project Browser. Its name then turns blue in the Hierarchy to show that it’s connected to a prefab. Like this:

prefab

Now that you have a prefab, you can create as many copies as you need. Just drag and drop Openspot from the Prefabs folder in the Project Browser into the Scene view. Do this 11 times to make a total of 12 Openspot objects in the scene.

Now use the Inspector to set the positions of these 12 Openspot objects to the following coordinates:

  • (X:-5.2, Y:3.5, Z:0)
  • (X:-2.2, Y:3.5, Z:0)
  • (X:0.8, Y:3.5, Z:0)
  • (X:3.8, Y:3.5, Z:0)
  • (X:-3.8, Y:0.4, Z:0)
  • (X:-0.8, Y:0.4, Z:0)
  • (X:2.2, Y:0.4, Z:0)
  • (X:5.2, Y:0.4, Z:0)
  • (X:-5.2, Y:-3.0, Z:0)
  • (X:-2.2, Y:-3.0, Z:0)
  • (X:0.8, Y:-3.0, Z:0)
  • (X:3.8, Y:-3.0, Z:0)

When you’re done, your scene should look like this.

Spot positions for the tower defense game

Place Monsters

To make placing easier, the project’s Prefab folder contains a Monster prefab.

Monster prefab – Ready for use

Monster prefab - Ready for use

At this point, it consists of an empty game object with three different sprites and their shooting animations as their children.

Each sprite represents the monster at a different power level. The prefab also contains an Audio Source component, which you’ll trigger to play a sound whenever the monster shoots a laser.

You’ll now create a script that can place a Monster on an Openspot.

In the Project Browser, select Openspot in the Prefabs folder. In the Inspector, click Add Component, then choose New Script and name it PlaceMonster. Select C Sharp as the Language and click Create and Add. Because you added the script to the Openspot prefab all Openspots in your scene now also have the script attached. Neat!

Double click on the script to open it in your IDE. Then add these two variables:

public GameObject monsterPrefab;
private GameObject monster;

You’ll instantiate a copy of the object stored in monsterPrefab to create a monster, and store it in monster so you can manipulate it during the game.

One Monster Per Location

Add the following method to allow only one monster per location:

private bool CanPlaceMonster()
{
  return monster == null;
}

In CanPlaceMonster() you check whether the monster variable is still null. If so, it means there is currently no monster here and it’s okay to place one.

Now add the following code to actually place a monster when the player clicks this GameObject:

//1
void OnMouseUp()
{
  //2
  if (CanPlaceMonster())
  {
    //3
    monster = (GameObject) 
      Instantiate(monsterPrefab, transform.position, Quaternion.identity);
    //4
    AudioSource audioSource = gameObject.GetComponent<AudioSource>();
    audioSource.PlayOneShot(audioSource.clip);

    // TODO: Deduct gold
  }
}

This code places a monster on mouse click or tap. So how does this work?

  1. Unity automatically calls OnMouseUp when a player taps a GameObject’s physics collider.
  2. When called, this method places a new monster if CanPlaceMonster() returns true.
  3. You create the monster with Instantiate, a method that creates an instance of a given prefab with the specified position and rotation. In this case, you copy monsterPrefab, give it the current GameObject’s position and no rotation, cast the result to a GameObject and store it in monster.
  4. Finally, you call PlayOneShot to play the sound effect attached to the object’s AudioSource component.

Now your PlaceMonster script can place a new monster, but you still have to specify the prefab.

Jeff Fisher

Contributors

Jeff Fisher

Author

Barbara Reichart

Author

Mitch Allen

Tech Editor

Sean Duffy

Final Pass Editor

Over 300 content creators. Join our team.