Unity日记22(携程概念)

 

目录

学习视频

携程

1异步

2调用方法

3优点

4停止方法

         5返回值

实例:每过一秒打印当前运行时间

实例:停止数字打印携程

错误方法:(携程只能开一个)

参考方法


学习视频

https://www.bilibili.com/video/BV1eu411U7EL/?spm_id_from=333.337.search-card.all.click&vd_source=ab35b4ab4f3968642ce6c3f773f85138

携程

是一个返回值是IEnumerator的函数,异是一个步多任务处理的函数

异步

异步多任务处理:穿插处理任务

异步意味着不停止就会运行。

调用方法

startcoroutine(方法)

startcoroutine(方法名)

优点

代替update的方法:update方法,每帧执行一次,非常消耗内存。

停止方法

StopCoroutine(方法名)

StopAllCoroutines()

 

返回值

实例:每过一秒打印当前运行时间

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IEnumer : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Timer());
    }

    IEnumerator Timer()
    {
        int count = 0;
        while (true)
        {
            yield return new WaitForSeconds(1);
            count++;
            Debug.Log(count);
        }
    }
}

实例:停止数字打印携程

判断成功标准:不再打印数字

错误方法:(携程只能开一个)

Func_Controller没把Timer停下来

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IEnumer : MonoBehaviour
{
    int count = 0;
    void Start()
    {
        StartCoroutine(Timer());

        StopCoroutine(Func_Controller());//5秒后停止指定携程
        
    }

    IEnumerator Timer()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            count++;
            Debug.Log(count);
        }
    }

    IEnumerator Func_Controller()
    {
        if (count >= 5)
        {
            StopCoroutine(Timer());
            Debug.Log("STOP");
            yield return 1;
        }
    }
}

参考方法

在TImer里面写,在同一个携程内实现停止自身。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IEnumer : MonoBehaviour
{
    int count = 0;
    void Start()
    {
        StartCoroutine(Timer());
    }

    IEnumerator Timer()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);//等一秒
            count++;
            Debug.Log(count);
            if (count >= 5)
            {
                StopCoroutine(Timer());
                Debug.Log("STOP");
                yield break;
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值