在继续使用函数 C# Unity 之前等待协程完成 [英] Wait for a coroutine to finish before moving on with the function C# Unity

查看:148
本文介绍了在继续使用函数 C# Unity 之前等待协程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Unity2d 中使一个单位在网格中移动.我让运动毫无问题地工作.我希望函数 MovePlayer 等到协程完成后再继续,所以程序会等到玩家完成移动后再发出更多命令.

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 is finished before moving on, so the program will wait until the player has finished the movement before issuing more orders.

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

Here is my code: public class Player : 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;
    }

}

推荐答案

不能在主线程的函数中等待协程,否则你的游戏会死机,直到你的函数结束.

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
}

这篇关于在继续使用函数 C# Unity 之前等待协程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆