- Home /
Enemy ai Multiple targets
I have been working on the following code and it works nice so far for what I am wanting but the issue I have hit is I want it to record if more then one enemy entered it's zone and if the first one dies or leaves zone switch to next if it is still in the zone.
Here is my code:
using UnityEngine;
using System.Collections;
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.
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.
target = myTransform;
}
void Start ()
{
}
void Update ()
{
//float distance = Vector3.Distance(target.transform.position, transform.position);
//if(distance < detectionDistance)
//{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);//Makes it look at us using the speed we set over time.
//Move to player.
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
//}
}
void OnTriggerEnter(Collider other) //When collided
{
if(other.tag == "Player")
{
target = other.transform;
}
}
void OnTriggerExit(Collider other) //When collided
{
if(other.tag == "Player")
{
target = myTransform;
}
}
}
Answer by Xtro · Aug 21, 2013 at 01:41 PM
C#
public List<Transform> targets = new List<Transform>();
when enter:
targets.Add( the entered object's transform here );
when exit:
targets.Remove( the exited object's transform here );
all other places, just use targets[0] instead of target.
instead of null check, just check against list count:
if (targets.count>0) ....bla bla target[0] bla bla...
I get this error on the last part :
Assets/SpaceUnity/_Scenes/EnemyAi.cs(32,29): error CS1061: Type System.Collections.Generic.List' does not contain a definition for
count' and no extension method count' of type
System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)
Your answer
![](https://koobas.hobune.stream/wayback/20220613112651im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How make script many people 0 Answers
AI in unity, need help 1 Answer
Distribute terrain in zones 3 Answers