- Home /
WaitForSeconds not working C#
Hello there!
I'm instantiating coins randomly but I want to wait until the coins are added to the to the coin's count. I don't know why my code isn't working:
//Instantiate a random number of coins and wait for add it to count
void AddCoins(){
StartCoroutine(Wait(1.0f));
for (int i = 0; i < ReturnRandomCoin(coinsEarned); i++){
GameObject NewCoin = (GameObject)Instantiate(myCoin, transform.position, Quaternion.identity);
}
}
//Calculate a random number
int ReturnRandomCoin(int RandomCoin){
int ret;
ret = Random.Range(3,7);
return ret;
}
//Wait for Adding the coin
IEnumerator Wait(float seconds){
yield return new WaitForSeconds(seconds);
playerScript.coins ++;
}
Anyway if I start the coroutine in Start() function it works, but if I do from my own void AddCoins() it never add the coins. What I am doing wrong?
Answer by Bioinformatizer · Jul 04, 2015 at 08:07 PM
First try adding "Debug.Log("add coins started"); to the line right before the StartCoroutine line to see if the function runs. My suspicion would be that the issue is in how you call AddCoins. If that is not the case, then you may need to move the "playerScript.coins ++;" to after the above mentioned line. as it is written the Ienumerator is returning to the coroutine that started before it gets there.
Definitely, it isn't the way I was calling AddCoins, because it was making the Instantite well. But finally I fixed the problem. Coroutine was working well but never get to an end because the gameobject was auto-destroyed above(from other script).