Move 2D gameobject to another one smoothly?

I’m trying to recreate the same effect that Among Us has in its main menu, where the crewmates move across the screen seemingly randomly. I’m trying to make my game object move to a random object in the array called nodes. However, after doing this, the guy moves very quickly, and increasing the movementTime variable crashes Unity. Anyone able to give me a suggestion?

    private void Update()
    {
        if (!moving)
        {
            moving = true;
            int timeToWait = Random.Range(0, 3);
            StartCoroutine(Move());
        }
    }

    IEnumerator Move()
    {
        float movementTime = 5f;
        float currentMovementTime = 0;
        int endPoint = Random.Range(0, nodes.Length);
        while (Vector2.Distance(transform.localPosition, nodes.ElementAt(endPoint).position) > 0)
        {
            currentMovementTime += Time.deltaTime;
            transform.localPosition = Vector3.Lerp(transform.position, nodes.ElementAt(endPoint).position,
                currentMovementTime / movementTime);
        }
        moving = false;
        yield return null;
    }

You need to put a yield return null; somewhere within your while loop.

Unity locks up until your code either returns or yields. Your entire while loop occurs while the game is frozen, all in one frame, because there is no yield inside of it.

omg thank you sooo much! you made my school project come along so much better! thanks for the help, have a great day king

1 Like