4

オブジェクトを時間の経過とともに移動させる拡張メソッドを作成しました。それはうまくいきます。ただし、オブジェクトは一定期間にわたってそのタスクを実行しているため、更新メソッドなどの他のすべての呼び出しを無視しています。コルーチンで何かをする必要があると思いますが、それがどこに行くのかわかりません。他のコード (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));
    }
}
4

1 に答える 1