gpt4 book ai didi

c# - 在继续使用函数 C# Unity 之前等待协程完成

转载 作者:太空狗 更新时间:2023-10-29 23:12:42 24 4
gpt4 key购买 nike

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

这是我的代码:公共(public)类播放器: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;
}

}

最佳答案

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

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

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# - 在继续使用函数 C# Unity 之前等待协程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44359236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com