当 class 不是 MonoBehaviour 时启动协程

Start coroutines when the class is not a MonoBehaviour

编辑: 解决这个问题的答案确实在 post 的答案中,它的副本就是这个。如果您遇到与标题相同的问题,请参考其他post。

我制作了一个简单的装备,可以像这样随着时间的推移移动东西:

 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。如果我的 class 是 NOT 一个 MonoBehaviour,如何从它开始一个 coroutine

或者如果这不可能,如何实例化 class是ARE MonoBehaviour?我注意到 _use AddComponent,但是 classes 是 而不是 组件。它们被另一个组件使用,不会被 inspector 放在 GameObject 上。

您不能从 MonoBehaviour 之外的 class 启动协程,因为方法 StartCoroutine()class[ 的一部分=25=]。 只需创建一个新的 GameObject,然后将您的 class 添加为 Component 即可

您可以实例化继承自 MonoBehaviour 的 class(对于此示例 MyClass),如下所示:

GameObject baseObject = new GameObject();
baseObject.AddComponent<MyClass>();

例如参见singleton pattern

Coroutines 必须绑定到 MonoBehaviour。或者换句话说,你将需要至少一个 MonoBehaviour 来开始一个 coroutine。遗憾的是,您无法实例化 MonoBehaviour:

var mono = new MonoBehaviour(); // will not work

我现在可以想到一个解决方法。您像往常一样编写 coroutine,然后从继承自 MonoBehaviour 的另一个 class 开始。也就是说,一个函数只需要 return IEnumerator 就可以启动为 Coroutine.

If another is started, the already started coroutine is stopped and a new one is called

想做里面一个non-MonoBehaviourclass恐怕不行

Remember: You will need at least one MonoBehaviour to start a coroutine.

我将称之为您想要实现的功能:Coroutine Management 功能,我的理解是您想将该功能包含在您的 non-MonoBehaviour class 中。但是多亏了我上面的 Remember 引用,您现在不能这样做。

但包括它 in-side 一个 .dll 可能是可能的,因为一个 .dll 可以包含许多 class。您可以使用 Access Modifiers 来执行您的规则(我最喜欢 internal 修饰符)。

如果我是你,我会将 Coroutine Management 视为一个单独的问题,并构建一个 .dll 来单独处理它们,这样它就不会扰乱我的 game-play 业务。