using UnityEngine; using System.Collections; /* 第三种:协程 原理: 注意: */ public class NewBehaviourScript : MonoBehaviour { void Update () { if (Input.GetKeyDown(KeyCode.Mouse0))//按下鼠标左键开始计时 { StartCoroutine(Timers(3)); } } IEnumerator Timers(int seconds)//rote为计时的间隔 { //第一种 for (float time = 0; time < seconds; time += Time.deltaTime)//计时seconds秒 { yield return null;//等到下一帧,null/任何数字都行,表示一个意思 } Debug.Log("计时" + seconds + "秒"); //第二种 yield return new WaitForSeconds(seconds); Debug.Log("计时" + seconds + "秒"); } }
//第一种:Time计时,计时期间不能中断//1.:通过Time.DateTime累加计时 Using UnityEngine; Using System.Collections; public Class Timer:Monobehaviour { private float timer=0;//计时变量 publi int time=1;//计时频率 void Update() { timer+=Time.deltaTime; if(timer>time) { timer=0;//计时器清零 Debug.Log("计时1次"); } }
using UnityEngine; using System.Collections; /* 2. 原理:利用Time.time-StartTime>需要维护开始时间 */ public class NewBehaviourScript : MonoBehaviour { float startTime;//开始计时时间 bool isStart;//是否计时 void Update () { if (Input.GetKey(KeyCode.Mouse0))//按下鼠标左键开始计时 { Timers(2); } } void Timers(float rote)//rote为计时的间隔 { if (isStart) { if ((Time.time - startTime) >= rote) { Debug.Log("计" + rote + "秒完成"); isStart = false;//计时完毕,将计时标志位设置false,停止本次计时 } } else//开始计时,记录开始的时间 { startTime = Time.time; isStart = true;//将标准位设置true } } }
using UnityEngine; using System.Collections; /* 第二种:Invoke() 原理:利用回掉函数(Invoke()) 注意:1.invoke()/InvokerRepeating()延时几秒调用某个方法,但是该方法必须是无参的,否则不能执行 2.他不许要向利用Time计时那样,不能中断。调用一次就是延时几秒 */ public class NewBehaviourScript : MonoBehaviour { void Update () { if (Input.GetKeyDown(KeyCode.Mouse0))//按下鼠标左键开始计时 { Invoke("Timers", 1); } } void Timers()//rote为计时的间隔 { Debug.Log("S计时一次完成"); } }
}
Unity的几中计时器
最新推荐文章于 2024-01-06 16:39:14 发布