UnityAPI——Coroutine

本文详细介绍了Unity引擎中的协程(Coroutine)概念及其使用方法,包括如何启动、停止协程。通过示例展示了协程在物体颜色渐变和控制流程中的应用,同时讲解了StopCoroutine和StopAllCoroutines的区别和用法。协程作为一种轻量级的多任务处理方式,允许在游戏逻辑中实现更复杂的定时和同步操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Coroutine

类似多线程的一种操纵,是一个协程函数

协程方法开启后,会继续运行下面的代码,不会等协程方法运行结束才继续执行

1.返回值是IEnumerator

2.返回参数的时候使用yield return null/0;

3.携程方法的调用StartCoroutine(调用的方法())

    void Start()
    {
        Debug.Log(1);
        StartCoroutine(ChageColor());
        Debug.Log(2);
    }

    IEnumerator ChageColor()
    {
        Debug.Log(3);
        yield return new WaitForSeconds(3);  //暂停3s
        GameObject go = GameObject.Find("Quad");
        go.GetComponent<MeshRenderer>().material.color = Color.black;
        Debug.Log(4);
        yield return null;
    }

 

使用协程完成物体颜色的渐变

      private void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            StartCoroutine(FadeChangeColor());
        }
    }
    IEnumerator FadeChangeColor()
    {
        Debug.Log(5);
        while (true)
        {
            GameObject go = GameObject.Find("Quad");
            Color color = go.GetComponent<MeshRenderer>().material.color;
            //使得颜色渐变的函数Lerp
            Color newColor = Color.Lerp(color, Color.blue, 0.02f);
            go.GetComponent<MeshRenderer>().material.color = newColor;
            yield return new WaitForSeconds(0.02f);
            Debug.Log(newColor.b);
            if(Mathf.Abs(Color.blue.b + newColor.b) >= 1.9f)
            {
                break;
            }
        }     
        yield return null;
    }

 

StopCoroutine

StopAllCoroutines

        前者停止指定的协程,后者是停止所有的协程

        之前的StartCoroutine是什么形式,StopCoroutine也要什么形式

        StartCoroutine("ChageColor");
        StopCoroutine("ChageColor");
        private IEnumerator ie;
        if (Input.GetKeyDown(KeyCode.A))
        {
            ie = FadeChangeColor();
            StartCoroutine(ie);
        }
        if (Input.GetKeyDown(KeyCode.B))
        {
            StopCoroutine(ie);
            Debug.Log("stop");
        }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值