前言:在坦克英豪项目中,有很多倒计时,当倒计时完毕时,需要执行事件。大部分倒计时的功能实现使用了协同,然而发现当面板关闭后,有部分应该关闭的功能却执行力,导致了一些错误。于是怀疑,协同并没有随面板隐藏而停止。
在unity5.3.5中,测试以下代码:
using UnityEngine;
using System.Collections;
/// <summary>
/// 测试线程
/// </summary>
public class TestCoroutine : MonoBehaviour {
public float waitTime = 5f;
private string funName = "TestByName";
void Start() {
StartCoroutine(funName);
StartCoroutine(TestByFun());
}
void OnDisable() {
StopCoroutine(funName);
StopCoroutine(TestByFun());
}
private IEnumerator TestByName() {
Debug.Log("start TestByName");
yield return new WaitForSeconds(waitTime);
Debug.Log("run TestByName");
}
private IEnumerator TestByFun() {
Debug.Log("start TestByFun");
yield return new WaitForSeconds(waitTime);
Debug.Log("run TestByFun");
}
}
/// <summary>
/// 测试销毁一个挂了协同的预制体,对应的功能是否终止掉。
/// </summary>
public class TestDestroy : MonoBehaviour {
public GameObject testPrefab = null;
private GameObject testObj = null;
IEnumerator Start() {
Debug.Log("create----");
testObj = Instantiate(testPrefab);
yield return new WaitForSeconds(1f);
// Destroy(testObj);
}
}
新建一个场景,创建一个空物体,挂 TestCoroutine.cs脚本,拖拽为预制体Test。然后通过在面板里面关闭脚本测试隐藏是中止协同功能,以及销毁testObj测试销毁物体是否终止协同。
项目代码:http://download.csdn.net/detail/xj1009420846/9601680
测试结论:
1. 调用 StopCoroutine(TestByFun()); 中的协同函数并无法中断
只能使用名字中断: StartCoroutine(funName);
2.隐藏脚本,并无法停止协同,所以使用协同时在OnDisable, OnDestroy里面必须添加中断代码。
3.销毁脚本,可以终止协同。