如何在非Monobehaviour類的實例中傳遞Monobehaviour?我發現這個link TonyLi提到你可以通過Monobehaviour在一個類的實例中啓動和停止協程,但是他沒有告訴你如何做到這一點。他這樣做了event.StartEvent(myMonoBehaviour);但他沒有顯示他從哪裏得到我的單子。我在互聯網上四處張望,但我似乎無法找到如何。在非MonoBehaviour類中使用協程
- 編輯
這裏就是我要做的。我想在一個類的實例中運行一個協程。我也希望能夠在課堂中停止協程。我想這樣做,這樣我的場景中就沒有任何擁有大型管理器的對象,並且我可以重複使用代碼來處理任何想要以這種方式乒乓的對象。該代碼向一個方向移動一個GameObject,然後休息並將其移向另一個方向並再次休息等。但是我無法從課程外部啓動協程。
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
}
}
是的,我會在一瞬間對我的問題進行補充。 –
我重新修改了這個問題。 –
查看我離開的答案。你可以使用'this'關鍵字。 – Programmer