我有一个基于网格的游戏,我在其中编写了我的移动脚本,以逐个单元格移动我的游戏对象。为了实现我想要的细胞移动,我不得不使用协同程序。
这是我的代码的伪代码片段:
private Coroutine currentCoroutine;
public void Move(Vector3 velocity)
{
currentCoroutine = StartCoroutine(MoveCoroutine(velocity));
}
private IEnumerator MoveCoroutine(Vector3 velocity)
{
Vector3 endPoint;
Vector3 nextVelocity;
if(velocity == Vector3.Right)
{
endPoint = rightEndPoint;
// object should move left in the next coroutine
nextVelocity = Vector3.Left;
}
else
{
endPoint = leftEndPoint;
// object should move right in the next coroutine
nextVelocity = Vector3.Right;
}
while(currentPos != endPoint)
{
currentPos += velocity
yield return new WaitForSeconds(movementDelay);
}
currentCoroutine = StartCoroutine(MoveCoroutine(nextVelocity));
}
基本上这样做是左右移动我的物体。如果它已经到达左边缘,我会向右移动,反之亦然。我从另一个脚本调用Move()
。
这段代码对我来说很好。但是,我不确定在协程中开始新的协程是否安全,就像我在这里所做的那样。在编写这样的协程时会有什么后果吗?我仍然习惯了协同程序的概念。
由于
答案 0 :(得分:1)
在协程末尾开始新的协程是安全的。顺便说一句,我注意到你的yield语句只在while循环中调用。如果while循环没有机会至少运行一次,那么你就会出错;所有协同程序都必须执行一个yield语句。