0
\$\begingroup\$

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;
}

}

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

you might try having the on enter adding the enemy to a 'target list', and on exit/killing enemy have that entry removed from the list.

using System.Collections.Generic; // lets use use the magical 'List' array

List<GameObject> targetedEnemies; // List arrays let us add and remove stuff later,
// that is, they do not have a maximum capacity and won't break from too many targets.

void OnTriggerEnter(Collider other)
{
    if(other.tag = "enemy")
    {
        targetedEnemies.Add (other.gameObject);
    }
}

void Update()
{
    foreach (GameObject target in targetedEnemies)
    {
        // take shot at target
        // check if target is still alive. If dead, remove from list
    }
}

void OnTriggerExit(Collider other)
{
    if(other.tag = "enemy")
    {
        targetedEnemies.Remove (other.gameObject);
    }
}

You could use a second gameObject placeholder to store the first target, and set the tower up in a way that it will focus on the first enemy that comes within range, and moves on to the next if the enemy dies.

You could also use OnTriggerStay() instead of OnTriggerEnter() to simply work every update function in which the target enemy is within the trigger collider, instead of the first.

\$\endgroup\$
4
  • \$\begingroup\$ This is currently my code pastebin.com/SJ2nfSdC. Whenever my minions enters the Sphere Collider i get this message NullReferenceException: Object reference not set to an instance of an object Tower.OnTriggerEnter (UnityEngine.Collider co) (at Assets/WorldObjects/Tower/Tower.cs:43) \$\endgroup\$ Commented Mar 29, 2015 at 13:13
  • \$\begingroup\$ Okay, I used OnTriggerStay() instead and it works perfectly as I wanted, thanks so much! However if you know why the List didn't work please share, as I think that method seems smarter. \$\endgroup\$ Commented Mar 29, 2015 at 14:22
  • \$\begingroup\$ You never instantiated the list. Create an Awake method and instantiate your list there. void Awake() { targetedEnemies = new List<GameObject>(); } \$\endgroup\$
    – fryBender
    Commented Mar 29, 2015 at 16:45
  • \$\begingroup\$ Oh man, I feel really stupid now... Thank you for noticing :) \$\endgroup\$ Commented Mar 29, 2015 at 23:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .