本文主要是介绍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 coroutineIEnumerator _countUp;//This will hold the counting down coroutineIEnumerator _countDown;//This is the coroutine we are currently//hijackingIEnumerator _current;//A value that will be updated by the coroutine//that is currently runningint value = 0;void Start(){//Create our count up coroutine_countUp = CountUp();//Create our count down coroutine_countDown = CountDown();//Start our own coroutine for the hijackStartCoroutine(DoHijack());}void Update(){//Show the current value on the screenguiText.text = value.ToString();}void OnGUI(){//Switch between the different functionsif(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 doif(_current != null && _current.MoveNext()){//Return whatever the coroutine yielded, so we will yield the//same thingyield return _current.Current;}else//Otherwise wait for the next frameyield return null;}}IEnumerator CountUp(){//We have a local increment so the routines//get independently faster depending on how//long they have been activefloat increment = 0;while(true){//Exit if the Q button is pressedif(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 instructionyield return new WaitForSeconds(0.1f);}}}
预览效果:
这篇关于Coroutine交叉调用实现计时器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!