- Home /
 
               Question by 
               davidflynn2 · Aug 21, 2013 at 03:40 PM · 
                c#errorai  
              
 
              Argument out of range.
I am using the following script to create an Enemy Ai the issue I have hit is if there is no target it gives me the Argument out of range. If I make it add its self to the array when there is no target the ai just starts to fly forward nonstop.
 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic; 
 
 public class EnemyAi : MonoBehaviour 
 {
     //public Transform target;//Targets.
     public int moveSpeed;//Speed enemy can move.
     public int rotationSpeed;//Speed enemy can rotate.
     public int detectionDistance;//The distance the enemy can detect you from.
     public List<Transform> targets = new List<Transform>();
     
     
     
     private Transform myTransform;//Save for the transform.
     
     void Awake()
     {
         myTransform = transform;//This saves our transform so we dont have to look it up all the time.    
         //targets.Add(myTransform);
     }
     
     
     void Update ()
     {
     
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targets[0].position - myTransform.position), rotationSpeed * Time.deltaTime);//Makes it look at us using the speed we set over time.
 
         myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
         
     }
     
      void OnTriggerEnter(Collider other) //When collided
     {
         if(other.tag == "Player")
         {
             targets.Add(other.transform);
             //targets.Remove(myTransform);
         }
         
         
     }
     void OnTriggerExit(Collider other) //When collided
     {
         if(other.tag == "Player")
         {
             targets.Remove(other.transform);
             //targets.Add(myTransform);
         }
         
         
     }
 }
 
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by whydoidoit · Aug 21, 2013 at 03:46 PM
At the start of Update check if the count is 0 and return if it is:
  void Update()
   {
        if(targets.Count < 1) return;
         ...
Ok so that sets the targets back to 0 again I see. Thanks for your help.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                