Wait for a coroutine to finish before moving on with the function C# Unity

前端 未结 1 1791
余生分开走
余生分开走 2020-12-07 02:13

I was working on making a unit move through a grid in Unity2d. I got the movement to work without problems. I would want the function MovePlayer to wait until the coroutine

相关标签:
1条回答
  • 2020-12-07 02:40

    You can not wait for a coroutine in a function in the main thread, otherwise your game will freeze until your function ends.

    Why don't you call your next step at the end of your coroutine?

    private IEnumerator SmoothMovement(List<Node> path)
    {
        float step = speed * Time.deltaTime;
    
        for (int i = 0; i < path.Count; i++)
        {
            targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);
    
            float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
    
            while (sqrRemainingDistance > float.Epsilon)
            {
                transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
                sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
                yield return null;
            }
    
            position = transform.position;
        }
        //Next Step
    }
    
    0 讨论(0)
提交回复
热议问题