Hi, I cant for the life of me figure out why my code is instantiating so many objects when I have a coroutine that makes you wait every 5 seconds before you can fire again. The first object takes about 5 seconds to instantiate and then it is just a constant stream of instantiated objects.
Heres what it looks like: it should just be one sphere at a time
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gorffrey_Data : MonoBehaviour
{
public GameObject EmpathySphere;
public GameObject HateSphere;
public Transform EnemyPosition;
public bool canFire = true;
//maybe have an enemymanager script that handles this stuff later
public int enemyMaxHealth = 20;
public int enemyCurrentHealth;
public int enemyStartingHealth = 5;
// Start is called before the first frame update
// Update is called once per frame
void Update()
{
if(canFire == true && enemyCurrentHealth != enemyMaxHealth)
{
Instantiate(HateSphere, EnemyPosition.position, EnemyPosition.rotation);
}
canFire = false;
StartCoroutine(RandomFire());
}
//coroutine to fire bullets in random interval
IEnumerator RandomFire()
{
yield return new WaitForSeconds(5);
canFire = true;
}
}