- Home /
How to get my targeting system working correctly
Hey i'm having some trouble with my turret script. Basically when the turret detects an enemy it projects an arrow at the enemy. When a new enemy enters the collider the turret targets the new enemy instead of continuing to fire at the original enemy till it is dead. How can I get the arrow to continue targeting the original enemy until it is either dead or has left the collider before it moves to the next target?
public class TurretArrowScript : MonoBehaviour {
public GameObject arrowPrefab; private GameObject Target; public float delayTime= 2.0f; public float lastFireTime=0.0f; public bool targetPresent=false; //public GameObject arrow;
void Start () {
}
// Update is called once per frame void Update () { if(targetPresent==true) { if (Time.time>lastFireTime + delayTime) { GameObject arrow =(GameObject)Instantiate(arrowPrefab, transform.position,transform.rotation); ArrowProjectileScript2 aps= arrow.GetComponent<ArrowProjectileScript2>(); aps.Target= Target; GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject enemy in enemies) { if(Target!=enemy){ Physics.IgnoreCollision(arrow.collider, enemy.collider); } } lastFireTime=Time.time; }
} } void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Enemy")
{
targetPresent=true;
Target = other.gameObject;
}
} void OnTriggerExit(Collider other) { if(other.gameObject==Target) { targetPresent=false; } }
}
Answer by Koder · Apr 01, 2011 at 01:45 AM
As for not targeting the new enemy...
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Enemy" && !targetPresent) { targetPresent=true; Target = other.gameObject;
}
}
But having it switch to the new target on enemies death is another matter. Upon enemies death you'd have to recheck target presence in trigger, probably by setting targetPresent back to false, which would then allow the trigger's if statement to set the new object. Then again I'm new to unity, but I'd try it, ^_^ Let me know lol.
Your answer
![](https://koobas.hobune.stream/wayback/20220613120102im_/https://answers.unity.com/themes/thub/images/avi.jpg)