using System.Collections;
using UnityEngine;
/*by Alexander*/
public class TestEnumerator : MonoBehaviour
{
bool isSomethingDone = false;
int counter = 0;
public void StartCorotineByBTN()
{
StartCoroutine(MyCoroutine());
MyThod();
}
void MyThod()
{
Debug.Log("counter started!");
//StopCoroutineByCounter();
StartCoroutine("CoroutineStoper");
Debug.Log("finished test!");
}
IEnumerator CoroutineStoper()
{
while (true)
{
if (counter > 5)
{
Debug.Log("Coroutine is going to be stopped!!!");
isSomethingDone = true;
StopCoroutine("MyCoroutine");
Debug.Log("Coroutine has been stopped!!!");
break;
}
else
{
yield return new WaitForSeconds(1f);
}
}
}
IEnumerator MyCoroutine()
{
while (true)
{
counter++;
Debug.Log("Done " + counter + " times!");
if (!isSomethingDone)
{
yield return new WaitForSeconds(1f);
}
else
{
break;
}
}
}
private void StopCoroutineByCounter()
{
// don't use in this way ! dangerous!!!
while (true)
{
if (counter > 5)
{
StopCoroutine("MyCoroutine");
break;
}
else
{
System.Threading.Thread.Sleep(1000);
}
}
}
}
运行结果如下:
作者:艾孜尔江
转载请务必标明出处!