Sponsored: A tower defense-style game in Unity (part 1)

July 17, 2015
protect

Author: by Dimitris-Ilias Gkanatsios, Tech Evangelist, Microsoft Greece

This tutorial is brought to you by Microsoft.

If you’re in a hurry, you can find the complete source code on GitHub, and the second part of the tutorial is posted here.

Unless you’ve been living in a cave in the recent years, you surely must have played a tower defense-style game. Be it Plants vs. Zombies, Kingdom Rush, geoDefense, Jelly Defense or any other, I’m sure you’ve spent much quality time setting up your defenses, killing enemies, and advancing stages.

So, since it’s one of the most common game types you can find on the application stores out there, I decided to try my luck and create one from scratch, using Unity3D, and present it in this tutorial. Since it’s a bit bigger compared to my previous efforts, it will be split in two parts. In this first post, we’ll describe the game, the level editor, the respective XML creation and parsing and the object pool used in the game to increase performance. Check the screenshot below to get a taste of how the game looks like, running on the Unity editor.

image

The scenario and gameplay are both pretty basic, actually. Badgers are attacking the player's bunny house and she has her Chuck Norris-trained bunnies to protect it, by shooting arrows. In order to be able to create more protector bunnies, the player needs carrot money. If the player kills all the badgers after the predetermined number of rounds, she wins. If enough badgers get into the bunny house, player loses! Badgers follow a path in order to approach the house upon which protector bunnies cannot be placed.

Let’s dive a bit deeper into the game mechanics and gameplay.

Bunny House: Initial life is 10, each badger that arrives If 10 badgers arrive at the house, game is over.

Path: The path that the badgers will walk on in order to arrive at the house. Specific waypoints will designate their direction.

Badger: Our enemy. It has a speed property and a health component, which is decreased when it is hit by an arrow. It follows waypoints (non-visible gameobjects) that are placed on the path pieces.

- Bunny: Our defense. It can shoot arrows at a constant fire rate. It starts its activity by looking for an enemy at a close vicinity. If it finds one, it starts shooting. If the enemy dies or leaves the vicinity, it searches for another enemy. Has a standard carrot cost to create.

Carrot: Falling randomly from the top of the screen. The player needs to tap/click on them in order to increase money, to create more bunnies.

BunnyGenerator: (Yeah, I could have come up with a better name.) It’s the bunny on the lower left part of the screen. The player needs to drag it in order to create new bunnies. On areas that a new bunny cannot be created (such as on the path), it will highlight them as red. Upon a new bunny creation, a standard amount of money will be taken of the player's account.

- Level Generator:  All game levels are to be stored in an XML file that uses a standard format. The Unity developer has the option to use a custom made Unity editor that saves the file from the scene editor to an XML file.

We also have a couple of “roles” that will be mentioned in this tutorial

Unity developer: The one that will use our custom editor to create new levels for the game

User/gamer: The end user that will enjoy our game!

Level Generator

The XML file structure

As we mentioned, all game levels are stored in an XML file. When we design something like this, we first need to determine the stuff that will be placed into it. Take a look at the Level1.xml file contents, located in Resources folder (in order to be able to pull its into during runtime).

imageimageimageimage

From the above picture, you can see that we store the initial money of the player, two variables to modify the spawn time for the carrots, the location of the bunny house (thereafter “Tower”), X and Y location for the PathPieces (the path that our enemies will walk on), X and Y location for the waypoints (that our enemies will follow in order to get to the bunny house), and a minor piece of information for each game Round.

Specifically, PathPieces contain information about the level path sprites and Waypoints to be used for empty GameObjects' creation that will “guide” the enemies to the Tower. The carrot spawn time will be randomly chosen each time and it will be clamped between the minimum and maximum values we set. Before we dive into the code, let's mention that game code was written in Visual Studio (check the free Community edition here). For debugging purposes, don't forget to check the Visual Studio tools for Unity here.

XML Parsing

All this information is mapped to the LevelStuffFromXML class.

image

We use the ReadXMLFile method to obtain information from the XML file at runtime. We could use serialization for the class but we instead chose LINQ to XML because 1. it rulezzz 2. its syntax is gorgeous! and 3. it allows for greater control of how your object stuff/properties are converted to XML and vice versa.

Consequently, we use the XDocument API to parse the Level1.xml file in the resources folder and create a LevelStuffFromXML instance, to be used in our game. Code used is pretty straightforward and self-explainable but, nevertheless, we use a top-down approach starting from the root XML element and traversing the tree to the bottom, fetching specific attributes and xml elements along the way. Should be pretty clear for you, even if you’re a beginner!

image

One may ask, why save on an XML file and not save each level into its own scene? Well, this could also be done. However, we opted to use this method for the following reasons:

  • XML is a human readable standard, can be altered without opening the Unity editor

  • Our game could possibly download new levels just by adding additional XML files to a server

  • Users/gamers could create new levels via a custom (non-Unity editor) and upload them on a community site, where users could rate and download

  • And, of course, pure educational reasons (that includes this tutorial’s own existence!)

Editor Window

So, you might ask, does one have to write the XML file by herself? Well, one could do that! However, we wanted to provide a convenient way for the Unity developer to create the XML file, so we created a small custom Unity editor window. If you open the project on Unity, you will see a new menu item titled “Custom editor” with a single command named “Export level”.

image

If you click on that, you will be presented with the below window:

image

By clicking on the “Add new round” button, you can create a new round that has specific number of enemies, based on the value of the below slider. Try it! After a few rounds’ addition, result can be like this:

image

That’s the way to create the rounds for our level. Of course, you can delete a round, if you made a mistake. Moreover, you can also modify values for initial money, the carrot spawn times and the desired filename for the exported level. If you try and export the level in an empty scene, you’ll be presented with the below error message.

image

Dear friends, 

JikGuard.com, a high-tech security service provider focusing on game protection and anti-cheat, is committed to helping game companies solve the problem of cheats and hacks, and providing deeply integrated encryption protection solutions for games.

Read More>>