如何在非 Monobehaviour 类的实例中传递 Monobehaviour?我找到了这个link https://forum.unity3d.com/threads/running-startcoroutine-from-a-non-monobehaviour.233817/TonyLi 提到您可以传递 Monobehaviour 来启动和停止类实例内的协程,但他没有展示如何做到这一点。他这样做了 theEvent.StartEvent(myMonoBehaviour);但他没有表明他从哪里得到我的单一行为。我在互联网上环顾四周,但似乎找不到方法。
这就是我正在尝试做的事情。我想在类的实例内运行协程。我还希望能够停止类实例内的协程。我想这样做,这样我的场景中就没有任何具有大型管理器的对象,并且这样我就可以重用我想要以这种方式进行乒乓球的任何对象的代码。代码将游戏对象向一个方向移动,然后休息一下,然后向另一个方向移动,然后再次休息,等等。但我无法从类外部启动协程。
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
}
}