Coroutine交叉调用实现计时器

主协程负责加载增数和减数两个协程,点击按钮在两协程间切换,按Q键退出协程的循环,通过GUIText显示协程能Value变化。

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections;
 
[RequireComponent(typeof(GUIText))]
public class Hijack : MonoBehaviour {
 
    //This will hold the counting up coroutine
    IEnumerator _countUp;
    //This will hold the counting down coroutine
    IEnumerator _countDown;
    //This is the coroutine we are currently
    //hijacking
    IEnumerator _current;
 
    //A value that will be updated by the coroutine
    //that is currently running
    int value = 0;
 
    void Start()
    {
        //Create our count up coroutine
        _countUp = CountUp();
        //Create our count down coroutine
        _countDown = CountDown();
        //Start our own coroutine for the hijack
        StartCoroutine(DoHijack());
    }
 
    void Update()
    {
        //Show the current value on the screen
        guiText.text = value.ToString();
    }
 
    void OnGUI()
    {
        //Switch between the different functions
        if(GUILayout.Button("Switch functions"))
        {
            if(_current == _countUp)
                _current = _countDown;
            else
                _current = _countUp;
        }
    }
 
    IEnumerator DoHijack()
    {
        while(true)
        {
            //Check if we have a current coroutine and MoveNext on it if we do
            if(_current != null && _current.MoveNext())
            {
                //Return whatever the coroutine yielded, so we will yield the
                //same thing
                yield return _current.Current;
            }
            else
                //Otherwise wait for the next frame
                yield return null;
        }
    }
 
    IEnumerator CountUp()
    {
        //We have a local increment so the routines
        //get independently faster depending on how
        //long they have been active
        float increment = 0;
        while(true)
        {
            //Exit if the Q button is pressed
            if(Input.GetKey(KeyCode.Q))
                break;
            increment+=Time.deltaTime;
            value += Mathf.RoundToInt(increment);
            yield return null;
        }
    }
 
    IEnumerator CountDown()
    {
        float increment = 0f;
        while(true)
        {
            if(Input.GetKey(KeyCode.Q))
                break;
            increment+=Time.deltaTime;
            value -= Mathf.RoundToInt(increment);
            //This coroutine returns a yield instruction
            yield return new WaitForSeconds(0.1f);
        }
    }
 

}

预览效果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值