- Home /
Problems with While Loops Only repeating Once
Hello, a fellow Unity use having time developing a basic clicker game, And having an error of course! I'm having this while loop in this coroutine, but it's only repeating once! It only running when the game starts, and here's the edited Script:
private void Start()
{
DataController.Instance.LoadItemButton(this);
StartCoroutine("AddGoldLoop");
UpdateUI();
}
IEnumerator AddGoldLoop()
{
Debug.Log("AddGoldLoop");
while (true)
{
Debug.Log("WHILE");
if (isPurchased)
{
Debug.Log("ISPURCHASED");
DataController.Instance.gold += goldPerSecond;
StartCoroutine ("BG");
}
Debug.Log("IFEND");
yield return new WaitForSeconds(1.0f);
}
}
There is a problem in "AddGoldLoop()" and I can't find out why. Thanks for Answering my question!
Hmm, that's odd. I tried the code and commented out the stuff I don't have, but the loop works for me. Try reducing the AddGoldLoop to just the base mechanics and see if that works? Like this:
IEnumerator AddGoldLoop() {
while (true) {
Debug.Log("Loop iteration");
yield return new WaitForSeconds(1.0f);
}
}
If this doesn't loop I'd be surprised.
See if the answers here https://answers.unity.com/questions/341663/problem-with-while-loop-in-coroutine.html can help you
Answer by GregoryFenn · Aug 04, 2018 at 10:38 AM
What does your BG coroutine do? Maybe that is setting isPurchased to false?
As a debug tip, can you add a counter for while loop, and print out Debug.Log(isPurchased) before and after? e.g. write this after your Start(){} method:
int c = 0;
IEnumerator AddGoldLoop()
{
c++;
Debug.Log(isPurchased.ToString() + ": " + c.ToString());
Debug.Log("AddGoldLoop");
while (true)
{
Debug.Log("WHILE");
c++;
Debug.Log(isPurchased.ToString() + ": " + c.ToString());
if (isPurchased)
{
Debug.Log("ISPURCHASED");
DataController.Instance.gold += goldPerSecond;
StartCoroutine ("BG");
c++;
Debug.Log(isPurchased.ToString() + ": " + c.ToString());
}
Debug.Log("IFEND");
c++;
Debug.Log(isPurchased.ToString() + ": " + c.ToString());
yield return new WaitForSeconds(1.0f);
}
}
This should help us find the issue, but I suspect its with your BG coroutine.
IEnumerator BG()
{
Debug.Log("BG");
I$$anonymous$$G.SetActive (true);
yield return new WaitForSeconds (.2f);
I$$anonymous$$G.SetActive (false);
}
It does this kinda things, to change the background image.