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][1]), 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][2]. [1]: http://www.pandabehaviour.com/ [2]: http://forum.unity3d.com/threads/ai-scripting-panda-bt-behaviour-tree-scripting.388429/
– ericbegue