在非MonoBehaviour类中使用coroutine

你怎么能在一个非Monobehaviour阶级的实例中通过Monobehaviour? 我找到了这个链接 ,TonyLi提到你可以通过一个Monobehaviour来开始和停止一个类的实例中的协同程序,但他没有说明你怎么能这样做。 他做了这个theEvent.StartEvent(myMonoBehaviour); 但是他并没有表明他从哪里获得了我的神经行为。 我在互联网上环顾四周,但我似乎无法找到。

  • 编辑

这是我想要做的。 我想在一个类的实例中运行一个协同程序。 我也希望能够在类的实例中停止协同程序。 我想这样做,以便我的场景中没有任何具有大型管理器的对象,以及我可以将代码重用于我想以这种方式打乒乓的任何对象。 代码在一个方向上移动一个Gameobject,然后rest并向另一个方向移动它并再次rest等等。但我不能从课外开始协同程序。

using UnityEngine; using System.Collections; using UnityEngine.UI; [RequireComponent (typeof(Image))] public class SpecialBar : MonoBehaviour { public float rangeX; public float breakTime; public float step; float startProgress = 0.5f; PingPongGameObject pingPonger; Color[] teamColors = new Color[]{new Color(255,136,0),new Color(0,170,255)}; void Start() { for(int i = 0; i < teamColors.Length; ++i) { teamColors[i] = StaticFunctions.NormalizeColor (teamColors[i]); } pingPonger = new PingPongGameObject (gameObject.transform.position, new Vector3(rangeX,0.0f,0.0f), gameObject, startProgress, breakTime, step ); } } 

第二堂课是我的协程所在的地方。

 public class PingPongGameObject { float step; Vector3 center; Vector3 range; GameObject ball; float progress; float breakTime; Vector3 endPos; Vector3 oppositePosition; public PingPongGameObject(Vector3 _center, Vector3 _range, GameObject _ball, float _startProgress, float _breakTime, float _step) { center = _center; range = _range; ball = _ball; progress = _startProgress; breakTime = _breakTime; step = _step; endPos = center - range; oppositePosition = center + range; // This is where I want to start the coroutine } public IEnumerator PingPong() { while (progress < 1) { progress += Time.deltaTime * step; Vector3 newPos = Vector3.Lerp (oppositePosition, endPos, progress); ball.transform.position = newPos; yield return null; } Vector3 temp = endPos; endPos = oppositePosition; oppositePosition = temp; progress = 0; yield return new WaitForSeconds (breakTime); yield return null; } public float Step { set{step = value;} } public void StopCoroutine() { // This is where I want to stop the coroutine } } 

TonyLi提到你可以通过一个Monobehaviour来启动和停止一个类的实例中的协同程序,但他没有说明你如何能做到这一点。 他这样做

你可以用this关键字做到这this 。 this关键字将获取MonoBehaviour的当前实例。

在这个例子中有一棵树,碰巧有一个组件MonoScript

在此处输入图像描述

MonoScript特定实例如果需要(因为它是ac#程序)可以实例化一般的c#类, NonMonoScript

通过MonoBehaviour类:

 public class MonoScript : MonoBehaviour { void Start() { NonMonoScript nonMonoScript = new NonMonoScript(); //Pass MonoBehaviour to non MonoBehaviour class nonMonoScript.monoParser(this); } } 

接收传递MonoBehaviour实例的类:

 public class NonMonoScript { public void monoParser(MonoBehaviour mono) { //We can now use StartCoroutine from MonoBehaviour in a non MonoBehaviour script mono.StartCoroutine(testFunction()); //And also use StopCoroutine function mono.StopCoroutine(testFunction()); } IEnumerator testFunction() { yield return new WaitForSeconds(3f); Debug.Log("Test!"); } } 

您还可以将monoParser函数中的mono参考存储在本地变量中以供重复使用。