- Home /
Infinite repetition, need help
Hey guys, I want to make an enemy activate a Bang! sprite using a Random.Range, but i've fallen into a infinte loop I'm unable to break out of. Any help is appreciated. I am using IEnumerators to do it, I think its the right way but I'm not sure.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DisparoEnemigo : MonoBehaviour {
public GameObject Bang;
[Range(0f, 10f)]
public float minTime = 2f;
[Range(0f, 10f)]
public float maxTime = 4f;
public float counter;
public bool bangActivo = false;
void Start()
{
counter = 5f;
}
void Update()
{
//Debug.Log(counter);
counter -= Time.deltaTime;
if (counter <= 0f)
{
//Prueba();
StartCoroutine(EsperarAlBang());
Debug.Log("if() 1 completado");
//counter = -1f;
}
if (bangActivo == true)
{
StartCoroutine(FueraBang());
Debug.Log("If() 2 completado");
}
}
IEnumerator EsperarAlBang() { yield return new WaitForSeconds(Random.Range(minTime, maxTime)); Bang.SetActive(true); Debug.Log("BangActivo true"); bangActivo = true; //Debug.Log("Ienumerator 1 completado"); }
IEnumerator FueraBang() { yield return new WaitForSeconds(5f); Bang.SetActive(false); bangActivo = false; counter = 5f; Debug.Log("Ienumerator 2 completado"); }
void Prueba()
{
}
}
Answer by yummy81 · Apr 28, 2020 at 02:53 PM
I reproduced your logic in one big coroutine. I think it is much cleaner, and hope it is what you want.
Regarding your code, you do not reset the counter, when it goes below 0f. You do it, but much later (far too late) in the second coroutine. With each frame counter falls deeper and deeper into negative territory, and as it is the condition of starting coroutine - with each frame starts new coroutine. Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisparoEnemigo : MonoBehaviour {
public GameObject Bang;
[Range(0f, 10f)]
public float minTime = 2f;
[Range(0f, 10f)]
public float maxTime = 4f;
float counter;
bool boo;
void Start()
{
counter = 5f;
boo = true;
}
void Update(){
if (boo){
StartCoroutine(OneBigCoroutine());
}
}
IEnumerator OneBigCoroutine(){
boo = false;
yield return new WaitForSeconds(counter);
yield return new WaitForSeconds(Random.Range(minTime, maxTime));
Bang.SetActive(true);
yield return new WaitForSeconds(5f);
Bang.SetActive(false);
boo = true;
}
}