I wrote an extension method to make an object move over time. The simplified version is as follows:
//This script gets attached to the GameObject
[RequireComponent(typeof(Rigidbody2D)]
public class MyBehaviour : MonoBehaviour
{
void Start()
{
rigidbody2D.MoveOverTime();
}
void Update(){
float newX = rigidbody2D.position.x;
float newy = rigidbody2D.position.y;
Vector2 newPosition = new Vector2(newX, newY);
rigidbody2D.MovePosition(newPosition); //Never called
}
}
=========================================================================================
//This script does not get attached to anything
public static class Rigidbody2DExtension
{
public static void MoveOverTime(this Rigidbody2D 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));
}
}
=========================================================================================
However, while my object is moving, it won’t do anything else. I am assuming I need to throw a Coroutine in there somewhere, but I cannot figure out where! How can I go about making this script work while still allowing for other code to run on the gameObject?