Unity_协同学习

前言:在坦克英豪项目中,有很多倒计时,当倒计时完毕时,需要执行事件。大部分倒计时的功能实现使用了协同,然而发现当面板关闭后,有部分应该关闭的功能却执行力,导致了一些错误。于是怀疑,协同并没有随面板隐藏而停止。


在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.销毁脚本,可以终止协同。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值