Home > Back-end >  The Coroutine pause code doesn't work in C#
The Coroutine pause code doesn't work in C#

Time:02-20

I am new to both C# and Unity and recently I began writing a game, but the program isn't able to read recognize my Coroutine, so the code excecutes itself very fast. Anyway here is the code:

void Update()
{
    x = Random.Range(-7.84f, 7.84f);
    y = Random.Range(-3.66f, 3.66f);
    z = 0;
    transform.position = new Vector3(x, y, z);
    StartCoroutine(timePause());  
}

IEnumerator timePause()
{

  yield return new WaitForSeconds(1);
  StartCoroutine(timePause());
}

CodePudding user response:

I'm guessing you want to change the position of an element over time every one second? If so, don't do it using Update (which is called every frame) but run corutine from Start method and do the change from corutine level where you wait for specified time and call it again.

Theoretically you could in the Update method check how much time has passed...but corutine will be easier in such a simple case.

void Start()
{
    StartCoroutine(timePause());  
}

IEnumerator timePause()
{
    yield return new WaitForSeconds(1);

    x = Random.Range(-7.84f, 7.84f);
    y = Random.Range(-3.66f, 3.66f);
    z = 0;
    transform.position = new Vector3(x, y, z);

    StartCoroutine(timePause());
}

CodePudding user response:

Calling StartCoroutine does not delay the method calling it!

What you rather want to do is wait within the Coroutine. In fact Start itself can be one and you can just loop forever like

IEnumerator Start()
{ 
    while(true)
    {
        x = Random.Range(-7.84f, 7.84f);
        y = Random.Range(-3.66f, 3.66f);
        transform.position = new Vector3(x, y);

        yield return new WaitForSeconds(1);
    }
}

which is basically the same as doing

private float timer;

void Update()
{ 
    timer  = Time.deltaTime;

    if(timer >= 1)
    {
        x = Random.Range(-7.84f, 7.84f);
        y = Random.Range(-3.66f, 3.66f);
        transform.position = new Vector3(x, y);
    }
}
  • Related