编辑:解决这个问题的答案确实在这个重复的帖子的答案中。如果您有相同的问题,在标题,请参阅另一篇文章。
我做了一个简单的钻机,可以长时间地移动东西,就像这样:
Transform from;
Transform to;
float overTime;
IUIAnimationEvent chain;
public delegate void UIchain();
public event UIchain NEXT_FUNCTION;
public MoveAction(Transform from, Transform to, float overTime, IUIAnimationEvent chain)
{
this.from = from;
this.to = to;
this.overTime = overTime;
this.chain = chain;
}
public void Move()
{
MonoBehaviour _lead = new MonoBehaviour();
if (moveRoutine != null)
{
_lead.StopCoroutine(moveRoutine);
}
moveRoutine = _Move(from, to, overTime);
_lead.StartCoroutine(moveRoutine);
}
IEnumerator _Move(Transform from, Transform to, float overTime)
{
Vector2 original = from.position;
float timer = 0.0f;
while (timer < overTime)
{
float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
from.position = Vector2.MoveTowards(from.position, to.position, step);
timer += Time.deltaTime;
yield return null;
}
if(NEXT_FUNCTION != null)
{
NEXT_FUNCTION();
}
}
但是,为了使它像我所希望的那样工作,我必须实例化它们,这样它们就不能是MonoBehaviour
。注意我对_lead
变量做了什么。我做到了这样我就可以像其他人一样启动coroutines
了。如果我的类是而不是a MonoBehaviour
,那么如何从它开始coroutine
?
或者如果不可能,如何实例化是 MonoBehaviour
的类?我注意到了_use AddComponent
,但是类是而不是组件。它们由另一个组件使用,不会由检查器安装在GameObject
上。
发布于 2017-02-07 13:22:28
Coroutines
必须绑定到MonoBehaviour
。换句话说,您至少需要一个MonoBehaviour
才能启动coroutine
。不幸的是,您无法实例化MonoBehaviour
var mono = new MonoBehaviour(); // will not work
我现在能想到一个解决办法。您可以像往常一样编写coroutine
,然后从从MonoBehaviour
继承的另一个类启动它。也就是说,函数只需要返回IEnumerator
才能作为Coroutine
启动。
如果另一个启动,已经启动的协同线将停止,并调用一个新的协同线。
如果您想要这样做,请在中使用non-MonoBehaviour
类,恐怕这是不可能的。
记住:启动
coroutine
至少需要一个MonoBehaviour
。
我将调用您想要实现的功能:Coroutine Management
特性,而我的理解是,您希望在non-MonoBehaviour
类中包含该特性。但是多亏了我上面的Remember
引语,你现在不能这么做。
但是将其包含在.dll
中可能是可能的,因为.dll
可以包含许多类。您可以使用访问修饰符强制执行规则( internal
修饰符是我最喜欢的)。
如果我是你,我会把Coroutine Management
当作一个单独的问题,并构建一个.dll
来分别处理它们,这样它就不会把我的游戏业务搞砸了。
发布于 2017-02-07 13:18:02
您不能从不是MonoBehaviour
的类启动协同线,因为方法StartCoroutine()
是该类的一部分。只需创建一个新的GameObject
,然后将类作为Component
添加到该类中即可。
您可以实例化从MonoBehaviour
继承的类(对于本例是MyClass
),如下所示:
GameObject baseObject = new GameObject();
baseObject.AddComponent<MyClass>();
例如,请参见单例模式
https://stackoverflow.com/questions/42090693
复制相似问题