My script targets enemies and fires at them when they are detected but only fires one arrow at them which is not enough to kill them so should fire again but I can’t get this to work!
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 () {
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
{
targetPresent=true;
Target = other.gameObject;
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;
}
}
}
}
Loop the fire function as long as enemy not dead/out of range?
Whats the best way to do that?
Create a boolean value for the class for whether the turret is alert or not, OnTriggerEnter should set this bool to true, and OnTriggerExit should set it to false.
Then all you need to do is put the existing code you have in OnTriggerEnter into the update function instead, and it should only run when the alert bool is true.
Thanks, the problem is solved for targeting the enemy again but another problem has arisen. 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. I was thinking maybe add the enemies into an array but i’m not sure if this would work and also how I can do this?
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;
}
}
}