【问题标题】:Wait for a coroutine to finish before moving on with the function C# Unity等待协程完成,然后继续使用 C# Unity 函数
【发布时间】:2017-11-05 15:41:51
【问题描述】:

我正在努力让一个单元在 Unity2d 中的网格中移动。我让运动正常工作。 我希望函数 MovePlayer 等到协程完成后再继续,所以程序会等到玩家完成移动后再发出更多命令。

这是我的代码: 公共类播放器:MonoBehaviour {

public Vector3 position;
private Vector3 targetPosition;

private float speed;

void Awake ()
{
    speed = 2.0f;
    position = gameObject.transform.position;
    targetPosition = position;
    GameManager.instance.AddPlayerToList(this);                     //Register this player with our instance of GameManager by adding it to a list of Player objects. 
}

//Function that moves the player, takes a list of nodes as path
public void MovePlayer(List<Node> path)
{
    StartCoroutine(SmoothMovement(path));
    //Next step should wait until SmoothMovement is finished
}

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;
    }

}

【问题讨论】:

    标签: c# coroutine unity2d


    【解决方案1】:

    您不能在主线程中的函数中等待协程,否则您的游戏将冻结,直到您的函数结束。

    为什么不在协程结束时调用下一步?

    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
    }
    

    【讨论】:

    • 谢谢你,你说的让我知道如何处理我的问题,谢谢:)
    • 旧帖子,但我认为为单个协程多次编写函数是不好的。
    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多