The code is not executing the expected thing.

Hello. I wanted this code to move the object 1x, wait 5 seconds, and then move it 3x. but instead of that, it instantly teleports object 4x. why does this happen and How can I fix it? thanks.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
       
        transform.Translate(new Vector3(1, 0, 0));

       
        StartCoroutine(WaitForSeconds());

      
        transform.Translate(new Vector3(3, 0, 0));
    }

    IEnumerator WaitForSeconds()
    {
        yield return new WaitForSeconds(5f);
    }
}

Coroutines don’t work that way.

Our very own Bunny83 has also provided a Coroutine Crash Course:

https://answers.unity.com/questions/1749615/coroutines-ienumerator-not-working-as-expected.html?childToView=1749714#answer-1749714

Coroutines in a nutshell:

Splitting up larger tasks in coroutines:

Coroutines are NOT always an appropriate solution: know when to use them!

1 Like

Your code is starting a coroutine that waits for 5 seconds, then terminates.

You need to put your logic in the coroutine!

3 Likes

In case it is not clear: the coroutine waits for 5 seconds but Start() is not, after starting the coroutine it continues with the next instruction.
Since Start() itself is a coroutine you can use the yield return… directly there.
But I recommend moving everything to the coroutine for more clarity and name it Delayed Movement or similar.