- Home /
Tower Defense Game Shooting Script Troubles
i have the following code:
void OnTriggerStay(Collider co)
{
if (co.GetComponent<Monster> ())
{
StartCoroutine(shoot());
mon = co.transform;
}
}
IEnumerator shoot(){
yield return new WaitForSeconds (1);
GameObject g = (GameObject)Instantiate (bulletPrefab, transform.position, Quaternion.identity);
g.GetComponent<Bullet> ().target = mon;
}
This is so that once an enemy walks into the trigger on my tower it starts shooting the monster. the current script makes many bullets shoot at one time and im not sure why because i added the "waitforseconds" any help would be greatly appreciated and as you i may be able to tell i am a begginer
Answer by DoTA_KAMIKADzE · Apr 26, 2015 at 11:22 PM
Well that is because you Start so many coroutines (1 each time OnTriggerStay is firing). With that code you should have initial delay of 1 sec and then massively fire your monster.
The easies way to fix that would be something like that:
private bool firing = false;
void OnTriggerStay(Collider co)
{
if (co.GetComponent<Monster>() && !firing)
{
firing = true;
StartCoroutine(shoot());
mon = co.transform;
}
}
IEnumerator shoot()
{
yield return new WaitForSeconds(1);
GameObject g = (GameObject)Instantiate(bulletPrefab, transform.position, Quaternion.identity);
g.GetComponent<Bullet>().target = mon;
firing = false;
}
If you don't like that approach then you can also make a cooldown with deltatime instead - check my answer HERE for an example.
P.S. The approach also highly depends on your logic of monster targeting (e.g. distance to tower or entrance turn, etc.). If you have some complex logic then you might want to manage everything yourself using OnTriggerEnter/Exit as well, but that's the whole different story.
Thank you so much! I tried doing something like that but I couldnt quite figure it out.
Your answer
Follow this Question
Related Questions
Checking if object intersects? 1 Answer
Removing all instantiated objects in scene 1 Answer
Bullet instantiates sometimes in wrong posiiton 0 Answers
Instantiate Reference Problem 1 Answer
Unet NetworkServer.Spawn() not working 5 Answers