- Home /
 
Shooting at the nearest enemy automatically.
Hi guys. I want to create a script which will automatically shoot at the nearest enemy. I have an enemies empty object which I spawn all of my enemies to (Every enemy is the child of enemies). It should work like a turret. I've already write it but it doesn't work correctly and I don't know why. It only shoot to a fix point. What do you think the problem is?
 using UnityEngine;
 using System.Collections;
 
 public class AllyAI : MonoBehaviour {
 
     public GameObject enemiesParent;
     public float Damage = 100;
     public GameObject Effect;
     public float fireRate = 10;
 
     private Transform nearestEnemy;
     private float nearestEnemyDistance;
 
     void Start()
     {
         nearestEnemyDistance = Mathf.Infinity;
     }
 
     void Update () {
         if (enemiesParent.transform.childCount > 0)
         {
             Shoot(NearestEnemy(enemiesParent));
         }
     }
 
     Transform NearestEnemy (GameObject Parent)
     {
         foreach (Transform child in Parent.transform)
         {
             float currentDistance = Vector3.Distance(this.transform.position, child.position);
             if (currentDistance < nearestEnemyDistance)
                 nearestEnemy = child;
         }
         return nearestEnemy;
     }
 
     void Shoot(Transform Target)
     {
         RaycastHit hit;
         Ray ray = Camera.main.ScreenPointToRay(Target.position);
 
         if (Physics.Raycast(ray, out hit))
         {
             GameObject effectClone = (GameObject)Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
             if (hit.transform.CompareTag("enemy"))
             {
                 hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.RequireReceiver);
             }
             Destroy(effectClone.gameObject, 1);
         }
 
     }
 
     IEnumerator Wait(float time)
     {
         yield return new WaitForSeconds(time);
         Debug.Log("Wait");
     }
     
 }
 
 
              Answer by NoseKills · Jan 31, 2015 at 10:22 PM
I don't see you resetting nearestEnemy or nearestEnemyDistance anywhere. Now the AI locks on to one enemy and probably shoots at it until it dies, but if it gets to let's say 1m from the turret, it won't lock on to new targets until they are under 1m away from it. (partly just guessing since i don't know what else your code does)
You should either reset them when the enemy dies or make them local variables inside nearestEnemy() function.
Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Make a simple reservoir (or tank, whatever you want to call it) 2 Answers
Using RayCast to do Continuous Shooting? 1 Answer
Turret Field of View? 1 Answer