- Home /
coroutine question c#
So I'm just beginning to learn about coroutines and how they work. I tried testing this code:
void Update()
{
transform.Translate(.05f, 0, 0);
}
inside a coroutine like so:
void Update ()
{
StartCoroutine(test());
}
IEnumerator test()
{
transform.Translate(.05f,0,0);
yield return null;
}
Do these two codes suppose to act the same way? Because the coroutine code seems to "choke" a couple of times at the beginning; it goes fast, slows down, then goes fast again. any help in understanding this would be great thx.
Answer by whydoidoit · Jan 09, 2013 at 08:01 AM
You shouldn't start a coroutine every update - it doesn't really do anything (apart from possibly run twice in the first frame) - but your coroutine does nothing useful - the yield return null has nothing following it (which is the part that would run on the next frame).
void Update()
{
if(Input.GetKeyDown("a"))
StartCoroutine(test());
}
IEnumerator test()
{
//Example
for(var i = 0; i < 20; i++)
{
transform.position += Vector3.right * Time.deltaTime;
yield return null;
}
}
Answer by cdrandin · Jan 26, 2013 at 08:40 PM
Make your own delay.
float timer;
int waitingTime;
void Update(){
timer += Time.deltaTime;
if(timer > waitingTime){
//Action
timer = 0;
}
}
You can probably do some code guru stuff, to allow functions to be parameters and just pass it to delay() function, which take parameters 1) function type and 2) delayTime, to allow the function to run with working in your own delay.