- Home /
Question by
kurpnieks2 · Feb 23, 2014 at 05:55 PM ·
coroutinesinvokerepeating
I don't understand coroutines and invoke
Hello,
I wanted to do a pretty simple task using c#- randomly assign one variables value every 5 seconds. I tried to use both coroutine and invoke but neither of them did work. It just assigns the value same way as if I hadn't used coroutines and invoke.
Here are the code versions I tried to do it with:
coroutine one:
void Update ()
{
StartCoroutine(randomNumber());
}
IEnumerator randomNumber()
{
y = Random.Range (1,10);
yield return new WaitForSeconds (5);
}
invoke one:
void Update ()
{
InvokeRepeating("randomNumber",1,5);
}
void randomNumber()
{
y = Random.Range (1,10);
}
If you can help me by explaining why it doesn't work I will greatly appreciate that.
Thank you.
Comment
Answer by YoungDeveloper · Feb 23, 2014 at 06:06 PM
This can be done a lot more simpler and shorter, try this:
void Start(){
StartCoroutine(RandomNumber());
}
//Will generate and print 5 numbers between 1 and 10, each after 2 seconds
IEnumerator RandomNumber(){
int num;
for(int i=0; i <5; i++){
num = Random.Range (1,10);
Debug.Log("New number: "+num);
yield return new WaitForSeconds(2);
}
}