我编写了一个扩展方法来使对象随时间移动。它运作良好;但是,由于对象在一段时间内执行该任务,它会忽略所有其他调用,例如我的更新方法。我假设我需要用协程做一些事情,但我无法弄清楚它的去向。如何在不阻止其他代码(例如 Update() 方法)同时运行的情况下使以下代码工作?简化版如下:
==================================================== =================================
//The following script is attached to the GameObject
[RequireComponent(typeof(Rigidbody2D)]
public class MyBehaviour : MonoBehaviour
{
void Start()
{
rigidbody2D.MoveOverTime();
}
void Update(){
rigidbody2D.MovePosition(transform.position.x + 1, transform.position.y);
}
}
==================================================== =================================
//The following script is not attached to anything
public static class Rigidbody2DExtension
{
public static void MoveOverTime(this Rigidbody2D rigidbody2D)
{
gameObject.addComponent<MoveOverTimeComponent>();
}
}
[RequireComponent(typeof(Rigidbody2D)]
class MoveOverTimeComponent : MonoBehaviour
{
void Update(){
MovePositionByALittleBit();
}
void MovePositionByALittleBit(){
float x = transform.position.x + 1;
float y = transform.position.y;
rigidbody2D.MovePosition(new Vector2(x, y));
}
}