I wrote an extension method to make an object move over time. It works well; however, because the object is performing that task over a period of time, it is ignoring all other calls, such as my update method. I am assuming I need to do something with a Coroutine, but I cannot figure out where it goes. How can I make the following code work without preventing other code (such as the Update() method) from running simulateneously? The simplified version is as follows:
==================================================================================
//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));
}
}
Both your Updates()
are running. In fact, all the Updates()
of all the MonoBehaviours
will run.
Assuming that gameObject.addComponent<MoveOverTimeComponent>();
actually refers to a GameObject
(which is not clear by the limited code you posted) then your problem is trying to move the same GameObject
on two different Update()
functions.