Coroutine Not working properly.
Hey everyone, I am trying to make an AI shooter script where I want the enemy to shoot once every 7 seconds. Then if the enemy reaches a certain point, he will shoot once every 3 seconds. However, the enemy doesn't wait 7 seconds to shoot, but rather he shoots like 20 bullet in less than a second (no joke). Can someone please tell me what I am doing wrong. I am a beginner btw. Here is my code.
void Update()
{
if (true)
{
StartCoroutine(Shoot());
}
if ((bossHealth.currentHealth <= 0) && (bossHealth2.currentHealth >0))
{
navMeshAgent2.speed = 10;
}
if ((bossHealth2.currentHealth <= 0) && (bossHealth.currentHealth > 0))
{
// shootTime = 2f;
}
}
IEnumerator Shoot()
{
if (projectile)
{
yield return new WaitForSeconds(7);
// Instantiante projectile at the camera + 1 meter forward with camera rotation
GameObject newProjectile = Instantiate(projectile, transform.position + transform.forward, transform.rotation) as GameObject;
// if the projectile does not have a rigidbody component, add one
if (!newProjectile.GetComponent<Rigidbody>())
{
newProjectile.AddComponent<Rigidbody>();
}
// Apply force to the newProjectile's Rigidbody component if it has one
newProjectile.GetComponent<Rigidbody>().AddForce(transform.forward * power, ForceMode.VelocityChange);
}
}
I suggest to learn about Behaviour Tree. It's a good alternative to coroutine to define logics that unfold in time.
Have a look at Panda BT (www.pandabehaviour.com), it's a script-based Behaviour Tree framework. The package contains an example that might interest you: it's a third person shooter with various enemy AIs.
If you have any question about using this tool do manage your AI, you're welcome on this thread.
Answer by YoungDeveloper · Jun 08, 2016 at 10:44 AM
if (true){
StartCoroutine(Shoot());
}
You are starting a coroutine every frame. Instead you should be starting one only if there isn't already one working, in your case you need only one at the time. You can do that by simple bool flag. Here's an example.
private bool corotineActive = false;
void Update(){
if(!corotineActive){
Debug.log("update found that no coroutine is running, launch one");
corotineActive = true;
StartCoroutine(Shoot());
}
}
IEnumerator Shoot(){
Debug.log("started");
yield return new WaitForSeconds(7);
corotineActive = false;
Debug.log("finished");
}