How can you pass a Monobehaviour inside an instance of a non Monobehaviour class? I found this link where TonyLi mentions that you can pass a Monobehaviour to start and stop coroutines inside a instance of a class, but he does not show how you can do that. He does this theEvent.StartEvent(myMonoBehaviour); but he does not show where he gets myMonobehaviour from. I looked around on the internet but I cannot seem to find how.
Here is what I am trying to do. I want to run a coroutine inside an instance of a class. I also want to be able to stop the coroutine inside the instance of the class. I want to do it this way so that I don't have any objects in my scene that have large managers and also so that I can reuse the code for any object that I want to pingpong in this way. The code moves a Gameobject in one direction then takes a break and moves it in the other direction and takes a break again etc. But I cannot start the coroutine from outside the class.
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
);
}
}
The second class is where my coroutine is in.
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
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…