说明:
本篇文章总结一下停止协程的方法,O(∩_∩)O哈哈哈~
步入正路:
Unity所提供的停止协程的接口:
//
// 摘要:
// ///
// Stops all coroutines running on this behaviour.
// ///
[WrapperlessIcall]
public void StopAllCoroutines();
//
// 摘要:
// ///
// Stops the first coroutine named /methodName/, or the coroutine stored in /routine/
// running on this behaviour.
// ///
//
// 参数:
// methodName:
// Name of coroutine.
//
// routine:
// Name of the function in code.
[WrapperlessIcall]
public void StopCoroutine(string methodName);
//
// 摘要:
// ///
// Stops the first coroutine named /methodName/, or the coroutine stored in /routine/
// running on this behaviour.
// ///
//
// 参数:
// methodName:
// Name of coroutine.
//
// routine:
// Name of the function in code.
public void StopCoroutine(IEnumerator routine);
public void StopCoroutine(Coroutine routine);
StopAllCoroutines():
用于停止当前脚本的所有协程
public void StopCoroutine(string methodName);
停止当前脚本中的某一个协程,通过协程的方法名查找并停止:
如下所示:
using UnityEngine;
using System.Collections;
/// <summary>
///测试 public void StopCoroutine(string methodName);
/// </summary>
public class TestHHH : MonoBehaviour
{
void Start()
{
//必须是——StartCoroutine(string methodName)方式
StartCoroutine("testStartCor");
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//对应——StartCoroutine(string methodName)方式
StopCoroutine("testStartCor");
}
}
IEnumerator testStartCor()
{
var cout = 0;
while (true)
{
yield return new WaitForSeconds(1);
cout++;
Debug.Log("StartCoroutine:" + cout);
}
}
}
局限性:StartCoroutine("testStartCor")中不能带参数,也就是testStartCor不能有参数,否则会报错:
Failed to call function testStartCor of class TestHHH
Calling function testStartCor with no parameters but the function requires 1.
UnityEngine.MonoBehaviour:StartCoroutine(String)
public void StopCoroutine(IEnumerator routine);
解决带参数的情况:
如下所示:
using UnityEngine;
using System.Collections;
/// <summary>
///测试 public void StopCoroutine(IEnumerator routine);
/// </summary>
public class TestHHH : MonoBehaviour
{
IEnumerator helloIenumeratro;
void Start()
{
//必须是——StopCoroutine(IEnumerator routine)方式
helloIenumeratro = testStartCor("今天的天气哈哈哈");
StartCoroutine(helloIenumeratro);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//对应——StopCoroutine(IEnumerator routine)方式
StopCoroutine(helloIenumeratro);
Debug.Log("已经停止协程");
}
}
IEnumerator testStartCor(string ss)
{
var cout = 0;
while (true)
{
yield return new WaitForSeconds(1);
cout++;
Debug.Log("StartCoroutine:" + cout+" "+ss);
}
}
}
测试如下所示: