【发布时间】:2015-11-27 22:01:17
【问题描述】:
我有一个基于网格的游戏,我在其中编写了我的移动脚本来逐个单元格地移动我的游戏对象。为了实现我想要的逐个单元移动,我不得不使用协程。
这是我的代码的伪代码sn-p:
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()。
这段代码对我来说很好用。但是,我不确定在协程中启动一个新的协程是否安全,就像我在这里所做的那样。写这样的协程有什么后果吗?我还在习惯协程的概念。
谢谢
【问题讨论】: