move inside a coroutine

Hi,

I want a simple camera moves into vent script. I never used coroutines before and want to make a point of using it for this to get to know them better.

It all runs in a single frame and I teleport into the vent. I know why it does this and understand that although it moves in the steps that I want, the steps all just happen in a single frame.

I basically just want to avoid having the Vector3.MoveTowards in the update in an if statement.

Any help would be greatly appreciated.

 {
  private IEnumerator EnterVent(Transform ventSpawn)
         {
     
             while (cam.position != ventSpawn.position)
             {
                 cam.position = Vector3.MoveTowards(cam.position, ventSpawn.position, speed);
             }
     
             this.gameObject.SetActive(false);
             ventPlayer.SetActive(true);
     
             return null;
         }
 }

That’s because you never tell the Coroutine to wait for the next frame to do the operation. Try adding yield return null; after cam.position = Vector3.MoveTowards(cam.position, ventSpawn.position, speed);

You can also check out my library for easier use of Coroutine: GitHub - SebastienAwali/SAction: A simple Unity C# script that wraps Unity's Coroutines, easily allowing developers to create and manage actions over time.

A coroutine will execute all the code before it returns, just like any other method. So you first need to add yield return null in your while statement.

You also shouldn’t compare floats and a Vector3 is just 3 floats at the end of the day so cam.position != ventSapwn.position will be true more than you like. Personally, I would use a lerp. like so;

    private IEnumerator EnterVent(Transform ventSpawn, float duration)
    {
        var startPos    = cam.position;
        var endPos      = ventSpawn.position;

        var t = 0f;

        while (t <= 1f)
        {
            cam.position = Vector3.Lerp(startPos, endPos, t);
            t += Time.deltaTime / duration;
            yield return null;
        }

        cam.position = endPos;

        this.gameObject.SetActive(false);
        ventPlayer.SetActive(true);
    }