Coroutine not working as expected
I'm trying to run a couple of coroutines that will ultimately do this: generate a random int and then start the attack function that corresponds to that int, then wait some amount of time before repeating the process.But for some reason the way my code is now random ints are being generated constantly so the enemy is just shooting every attack out extremely quickly. Can anyone help me find the flaw in my code?
private int[] elements;
private int myElement;
public float timeBetweenAttacks;
public bool runningCR;
public Transform wavePoint, slicePoint, shootPoint;
public bool runningAtk;
public GameObject bossAtkWave, bossAtkSlice, bossAtkShoot;
// Start is called before the first frame update
void Start()
{
elements = new int[3];
//BossBattleTrigger.instance = GetComponent<BossBattleTrigger>();
}
// Update is called once per frame
void Update()
{
if (!runningCR && !runningAtk)
{
StartCoroutine(ChooseAttack());
}
}
public IEnumerator ChooseAttack()
{
if (!runningAtk)
{
runningCR = true;
yield return new WaitForSeconds(timeBetweenAttacks * Time.deltaTime);
RandomNumberGenerator();
Debug.Log(myElement);
//Debug.Log(elements.Length);
switch (myElement)
{
case 0:
StartCoroutine(Wave());
break;
case 1:
StartCoroutine(Slice());
break;
case 2:
StartCoroutine(Shoot());
break;
}
//yield return new WaitForSeconds(timeBetweenAttacks * Time.deltaTime);
runningAtk = true;
runningCR = false;
} else if (runningAtk)
{
yield break;
}
}
public IEnumerator Wave()
{
//runningAtk = true;
//do atk stuff
Instantiate(bossAtkWave, wavePoint.transform.position, wavePoint.transform.rotation);
yield return new WaitForSeconds(timeBetweenAttacks * Time.deltaTime);
runningAtk = false;
//Debug.Log("Wave");
}
public IEnumerator Slice()
{
//runningAtk = true;
Instantiate(bossAtkSlice, slicePoint.transform.position, slicePoint.transform.rotation);
yield return new WaitForSeconds(timeBetweenAttacks * Time.deltaTime);
runningAtk = false;
//Debug.Log("SliceRunning");
}
public IEnumerator Shoot()
{
//runningAtk = true;
Instantiate(bossAtkShoot, shootPoint.transform.position, shootPoint.transform.rotation);
yield return new WaitForSeconds(timeBetweenAttacks * Time.deltaTime);
runningAtk = false;
//Debug.Log("ShootRunning");
}
private void RandomNumberGenerator()
{
myElement = Random.Range(0, elements.Length);
}
Answer by xxmariofer · Aug 31, 2021 at 07:05 AM
whats the value of timeBetweenAttacks? simply remove the Time.deltaTime, it makes no sense in your code, since that code, even if its running in the update, is not frame rate independant
I removed the Time.deltaTime from the script and it worked exactly as expected! Thank you, haha and sorry for the newbie mistake