How to Build a Tower Defense Game in Unity – Step by Step
In this article
Approx. 2‑3 weeks, low cost, medium difficulty – build a tower‑defense game in Unity using built‑in components and C# scripts.
Project Setup
Create a new 2D Unity project named TDGame. In the Project window, right‑click > Create > Folder and make subfolders: Scripts, Prefabs, Sprites, Scenes. Save the initial scene as MainScene.unity inside Scenes. Import the free 2D Pixel Art Pack or any royalty‑free sprite sheet for ground, towers, and enemies. Set the main camera to Orthographic, size 5, and lock its position at (0,0,‑10).
Tilemap and Path Design
Open Window > 2D > Tile Palette and create a new palette called GroundPalette. Drag ground sprites into the palette, then paint a rectangular grid of 20 × 12 tiles in the Scene view. Reserve a continuous lane of 1‑tile width for enemy movement; mark its start cell at (‑9, 0) and end cell at (9, 0). Add a TilemapCollider2D to the Tilemap and set its Used By Composite flag, then attach a CompositeCollider2D to the Grid object. This creates a single solid collider for the entire map.
Enemy Spawner and Pathing
Create an empty GameObject named Spawner at the start cell coordinates. Add a new C# script EnemySpawner.cs to the Scripts folder and attach it to the Spawner. In the script, define a public GameObject enemyPrefab, a float spawnInterval = 2f, and a int waveNumber = 1. Use InvokeRepeating("SpawnEnemy", 1f, spawnInterval) to begin spawning after one second. For pathing, add a Waypoint component to each tile along the lane; the component stores a Vector3 position. The enemy script reads the waypoint list and moves with transform.position = Vector3.MoveTowards(..., speed * Time.deltaTime). Set speed = 2 + 0.2 × waveNumber to increase difficulty per wave.
Turret Blueprint
Create a prefab named BasicTurret. Its hierarchy contains a SpriteRenderer for the visual, a CircleCollider2D set as trigger with radius 2.5 units, and an empty child Barrel to indicate firing direction. Attach a script Turret.cs that scans OnTriggerEnter2D for objects tagged Enemy. Store the nearest target in a private variable, rotate the Barrel toward the target using Mathf.Atan2, and fire a projectile prefab every fireRate = 1.0f seconds. Projectiles move at 5 units/s and destroy themselves on collision, dealing damage = 10 + 2 × waveNumber. Place a few turret instances manually in the scene to test range and line‑of‑sight.
Game Logic and Wave Management
Add a GameObject GameController with a script GameManager.cs. The manager tracks int playerLives = 20, int playerScore = 0, and bool isGameOver. Subscribe to an enemy’s OnReachGoal event; each call reduces playerLives by one and checks for zero to trigger GameOver(). When an enemy dies, raise OnEnemyKilled to add score += 100. After all enemies in a wave are cleared, increase waveNumber, reduce spawnInterval by 0.1 s (minimum 0.5 s), and call Spawner.StartNextWave(). Store persistent data with PlayerPrefs.SetInt("HighScore", playerScore) after a game ends.
UI, Scoring and Lives
Open Canvas > Create > UI > TextMeshPro – rename it ScoreText. Position it at the top‑left corner (‑8, 4) and set the text to Score: 0. Duplicate it for LivesText at the top‑right corner (8, 4) with Lives: 20. In GameManager.cs, add public TextMeshProUGUI scoreLabel, livesLabel; and update the labels each frame: scoreLabel.text = $"Score: {playerScore}"; and similarly for lives. Add a Button labeled Restart that calls SceneManager.LoadScene("MainScene"). Ensure the button is disabled until isGameOver becomes true.
Testing, Debugging and Polish
Enter Play mode and verify that enemies follow the waypoint line without clipping through the Tilemap collider. Use the Unity Profiler to watch CPU spikes; if frame time exceeds 16 ms, lower the number of active enemies per wave or reduce projectile count. Add particle systems to turret fire and enemy death for visual feedback; set Duration = 0.3 s and Start Lifetime = 0.2 s. Export the final build via File > Build Settings, select the target platform, and click Build. Test the build on the target device for input latency and audio volume.
Common Issues
| Symptom | Cause | Fix |
|---|---|---|
| Enemies pass through ground | TilemapCollider2D not set to "Used By Composite" | Enable the flag and attach a CompositeCollider2D to the Grid |
| Turrets never fire | Target tag mismatch or fireRate set to 0 | Tag enemies as "Enemy" and ensure fireRate > 0 |
| Game slows after several waves | Unreleased projectile objects accumulate | Call Destroy(gameObject) on projectile after collision or after 3 seconds |
| Score does not update | UI Text reference not assigned in inspector | Drag ScoreText and LivesText into the GameManager script fields |
Fit and Scale
| Parameter | Recommended Value | Reason |
|---|---|---|
| Tile size | 1 unit × 1 unit | Matches Unity's default grid and simplifies waypoint math |
| Enemy speed range | 2 – 4 units/s | Provides visible movement without overwhelming the player |
| Turret range | 2.5 units (circle collider radius) | Balances coverage and placement strategy |
| Wave enemy count | 5 + 2 × waveNumber | Linear scaling keeps difficulty predictable |
Following these steps yields a functional tower‑defense prototype that can be expanded with additional tower types, upgrade paths, and visual themes.