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

半世苍凉 提交于 2019-11-28 01:59: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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!