Hi guys and girls
Currently I’m trying to make a 3d tower defense game but now I’ve run into problems…
I’ve got these scripts, but when one of my turret kills an enemy it doesnt update how many enemies there’s alive in the scene. Looks like it doesnt execute my Die() function in Enemy.CS
Here’s my code:
Enemy.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public float startSpeed = 10f;
[HideInInspector]
public float speed;
public float health = 100;
private PlayerStats thePlayerStats;
public int expToGive;
public int worth = 50;
public GameObject deathEffect;
private bool isDead = false;
void Start()
{
speed = startSpeed;
thePlayerStats = FindObjectOfType<PlayerStats>();
}
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0)
{
Die();
}
}
public void Slow(float pct)
{
speed = startSpeed * (1f - pct);
}
void Die()
{
thePlayerStats.AddExperience(expToGive);
isDead = true;
PlayerStats.Money += worth;
GameObject effect = (GameObject)Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(effect, 5f);
WaveSpawner.EnemiesAlive--;
Destroy(gameObject);
}
}
Here’s my WaveSpawner.CS file:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class WaveSpawner : MonoBehaviour
{
public static int EnemiesAlive = 0;
public Wave[] waves;
public Transform spawnPoint;
public float timeBetweenWaves = 5f;
private float countdown = 2f;
public Text waveCountdownText;
public Text enemiesAliveText;
private int waveIndex = 0;
void OnEnable()
{
EnemiesAlive = 0;
}
void Update()
{
enemiesAliveText.text = "Enemies alive:" + EnemiesAlive;
if (EnemiesAlive > 0)
{
return;
}
if (waveIndex == waves.Length)
{
Debug.Log("LEVEL WON!");
this.enabled = false;
}
if (countdown <= 0f)
{
StartCoroutine(SpawnWave());
countdown = timeBetweenWaves;
return;
}
countdown -= Time.deltaTime;
countdown = Mathf.Clamp(countdown, 0f, Mathf.Infinity);
waveCountdownText.text = string.Format("{0:00:00}", countdown);
}
IEnumerator SpawnWave()
{
PlayerStats.Rounds++;
Wave wave = waves[waveIndex];
for (int i = 0; i < wave.count; i++)
{
SpawnEnemy(wave.enemy);
yield return new WaitForSeconds(1f / wave.rate);
}
for (int i = 0; i < wave.count; i++)
{
waveIndex++;
}
}
void SpawnEnemy(GameObject enemy)
{
Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
EnemiesAlive++;
}
}
And finally Wave.cs:
using UnityEngine;
[System.Serializable]
public class Wave{
public GameObject enemy;
public int count;
public float rate;
}
Thank you in advance!