So I've made a Tower script in c# that spawns a projectile that then fires at the enemy gameobject. However, because I'm using the OnTriggerEnter() function it will only fire as many times as gameObjects enters the collider.
How do I make sure that the tower will keep firing untill there is no more enemies within its collider?
public class Tower : MonoBehaviour {
// Public variables
public GameObject ammoPrefab;
public float reloadTime = 1f;
// Private variables
private Transform projectileTarget;
private GameObject projectile;
private float nextFireTime;
private float nextAnimTime;
void Update() {
if (projectileTarget) {
Debug.Log("We have target");
if(Time.time >= nextFireTime){
Debug.Log("nextFireTime has passed");
FireProjectile();
}
}
}
void OnTriggerEnter(Collider co) {
// Was it a Monster? Then Shoot it
if (co.gameObject.tag == "Enemy") {
Debug.Log("Enemy tag detected");
nextFireTime = (float)(Time.time+(reloadTime*0.5));
projectileTarget = FindClosestEnemy().gameObject.transform;
}
}
void OnTriggerExit(Collider co) {
}
void FireProjectile() {
Debug.Log ("Shoot");
nextFireTime = Time.time + reloadTime;
projectile = (GameObject)Instantiate (ammoPrefab, transform.position, ammoPrefab.transform.rotation);
projectile.GetComponent<Projectile> ().target = projectileTarget;
}
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}