Creating a well-architected Unity game, especially for a tower defense genre, involves breaking down the game into manageable components and using best practices like Object-Oriented Programming (OOP), organizing code into systems, and maintaining separation of concerns. Below is a basic outline with code for each component:
1. Game Manager
This will handle the game's main loop, spawning enemies, and managing waves.
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public GameObject[] enemyPrefabs;
public Transform enemySpawnPoint;
public float spawnInterval = 2f;
private void Awake()
{
Instance = this;
}
private void Start()
{
StartCoroutine(SpawnEnemies());
}
private IEnumerator SpawnEnemies()
{
while(true)
{
SpawnEnemy();
yield return new WaitForSeconds(spawnInterval);
}
}
private void SpawnEnemy()
{
int randomIndex = Random.Range(0, enemyPrefabs.Length);
Instantiate(enemyPrefabs[randomIndex], enemySpawnPoint.position, Quaternion.identity);
}
}
2. Player
Handles the player's score, lives, and other properties.
public class Player : MonoBehaviour
{
public static Player Instance;
public int lives = 10;
public int score = 0;
private void Awake()
{
Instance = this;
}
public void TakeDamage(int amount)
{
lives -= amount;
if (lives <= 0)
{
GameOver();
}
}
public void AddScore(int amount)
{
score += amount;
}
private void GameOver()
{
Debug.Log("Game Over!");
// Implement Game Over logic
}
}
3. Enemy
Manages enemy behavior including taking damage and attacking the player.
public class Enemy : MonoBehaviour
{
public int health = 10;
public int damage = 1;
public float speed = 1f;
private Transform target;
private void Start()
{
target = GameObject.Find("PlayerBase").transform; // Assuming there's a GameObject named PlayerBase
}
private void Update()
{
MoveTowardsTarget();
}
private void MoveTowardsTarget()
{
if(target != null)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0)
{
Die();
}
}
private void Die()
{
Destroy(gameObject);
Player.Instance.AddScore(10);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("PlayerBase"))
{
Player.Instance.TakeDamage(damage);
Destroy(gameObject);
}
}
}
4. Tower
Handles the tower's behavior including shooting at enemies.
public class Tower : MonoBehaviour
{
public float range = 5f;
public float fireRate = 1f;
public GameObject bulletPrefab;
public Transform firePoint;
private float fireCountdown = 0f;
private void Update()
{
fireCountdown -= Time.deltaTime;
if(fireCountdown <= 0f)
{
FindAndShootEnemy();
fireCountdown = 1f / fireRate;
}
}
private void FindAndShootEnemy()
{
Collider2D[] enemiesInRange = Physics2D.OverlapCircleAll(transform.position, range);
foreach(var enemy in enemiesInRange)
{
if(enemy.CompareTag("Enemy"))
{
Shoot(enemy.transform);
break;
}
}
}
private void Shoot(Transform enemy)
{
GameObject bulletGO = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Bullet bullet = bulletGO.GetComponent<Bullet>();
if(bullet != null)
{
bullet.Seek(enemy);
}
}
private void OnDrawGizmosSelected()
{
// Draw range gizmo for visualization
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}
5. Bullet
Manages the bullet's behavior including seeking and damaging enemies.
public class Bullet : MonoBehaviour
{
private Transform target;
public float speed = 10f;
public int damage = 10;
public void Seek(Transform _target)
{
target = _target;
}
private void Update()
{
if(target == null)
{
Destroy(gameObject);
return;
}
Vector3 direction = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
if(direction.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
transform.Translate(direction.normalized * distanceThisFrame, Space.World);
}
private void HitTarget()
{
Enemy enemy = target.GetComponent<Enemy>();
if(enemy != null)
{
enemy.TakeDamage(damage);
}
Destroy(gameObject);
}
}
6. UI Manager
Manages the game's user interface elements.
public class UIManager : MonoBehaviour
{
public Text livesText;
public Text scoreText;
private void Update()
{
livesText.text = "Lives: " + Player.Instance.lives;
scoreText.text = "Score: " + Player.Instance.score;
}
}
Summary
This is a basic framework and can be expanded. Make sure to place these scripts on appropriate GameObjects and set all necessary references in the Unity editor. For complex games, consider implementing advanced patterns like MVC (Model-View-Controller) or ECS (Entity Component System). This example provides a starting point, and you can build more functionalities like different tower types, enemy waves, upgrading systems, and more.