扩展方法中的协程
本文关键字:方法 扩展 | 更新日期: 2023-09-27 18:30:32
我编写了一个扩展方法来使对象随时间移动。 它运作良好;但是,由于对象在一段时间内执行该任务,因此它将忽略所有其他调用,例如我的更新方法。 我假设我需要用协程做一些事情,但我无法弄清楚它的去向。 如何在不阻止其他代码(例如 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));
}
}
您的两个Updates()
都在运行。事实上,所有MonoBehaviours
的所有Updates()
都将运行。
假设gameObject.addComponent<MoveOverTimeComponent>();
实际上指的是一个GameObject
(您发布的有限代码不清楚),那么您的问题就是尝试在两个不同的Update()
函数上移动相同的GameObject
。