Pac*_*ero 5 c# coroutine unity2d
我正在努力让一个单位在Unity2d中通过网格移动.我让运动顺利运转.我希望函数MovePlayer等到协程完成后再继续,所以程序将等到玩家完成移动后再发出更多订单.
这是我的代码: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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您不能等待主线程中的函数中的协程,否则您的游戏将冻结,直到您的函数结束.
为什么不在你的协程结束时给你的下一步打电话?
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
}
Run Code Online (Sandbox Code Playgroud)