- Home /
Turret still shooting after target is killed
I have a turret that shoots at its target, but even after the target is destroyed it will still shoot at the targets last position. I am wondering what change I have to make in order for this not to happen. Here is my code:
public class Turret : MonoBehaviour {
//public Transform target;
Transform player;
public Vector3 Restriction;
public Transform gunEnd;
public GameObject bullet;
// Use this for initialization
void Start ()
{
player = GameObject.FindWithTag("target").transform;
}
// Update is called once per frame
void Update ()
{
transform.LookAt (player);
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "target")
{
StartCoroutine ("Shooting");
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "target")
{
StopCoroutine("Shooting");
}
}
IEnumerator Shooting ()
{
while (true)
{
Instantiate (bullet, gunEnd.position, gunEnd.rotation);
yield return new WaitForSeconds (0.5f);
}
}
}
Answer by Strixie13 · Jul 21, 2018 at 07:29 PM
OnTriggerExit would not be triggered when you delete the game object. It would have to still be active when it leaves the collider.
public class Turret : MonoBehaviour {
//public Transform target;
Transform player;
public Vector3 Restriction;
public Transform gunEnd;
public GameObject bullet;
// Use this for initialization
void Start ()
{
player = GameObject.FindWithTag("target").transform;
}
// Update is called once per frame
void Update ()
{
transform.LookAt (player);
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "target")
{
StartCoroutine (Shooting(other.gameObject));
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "target")
{
StopCoroutine("Shooting");
}
}
IEnumerator Shooting (GameObject obj)
{
while (obj != null)
{
Instantiate (bullet, gunEnd.position, gunEnd.rotation);
yield return new WaitForSeconds (0.5f);
}
StopCoroutine("Shooting");
}
}
Try that. I added a reference to the game object that entered the collider. If it is destroyed, the while loop in your shooting coroutine should stop, move on to the stop coroutine line and stop shooting.
This worked well except it caused the turret to fire even when the target was out of range. I was able to solve this by adding a bool that deter$$anonymous$$ed if the target was in range and turning while (obj != null)
into while ((obj != null) && inRange == true)
You probably don't care, but incase anyone finds this and decides to use it for their game for whatever reason they might find it useful :P
This is all awesome info! Thanks @FaZe_Dankage