[Unity学习教程] Unity开发小本事(一)、计时器Timer

[复制链接]
查看1283 | 回复0 | 2023-8-23 11:56:41 | 显示全部楼层 |阅读模式 来自 中国北京
1.第一种计时器Time.deltaTime

Time.deltaTime为游戏每帧实行的时间,该方法一样寻常用加法来计时,原理是使用nity中Update方法的每帧实行的时间,按钮按下后不绝累加,大于计时时间时关闭,可根据实际使用环境进行加减,以下给出加法利用。
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TimeTest : MonoBehaviour
  6. {
  7.    
  8.     float totalTime = 3;
  9.     float timer = 0;
  10.     bool isStartTimer = false;
  11.     public Button button;
  12.     // Start is called before the first frame update
  13.     void Start()
  14.     {
  15.    
  16.         button.onClick.AddListener(OnClickBtn);
  17.     }
  18.     private void OnClickBtn()
  19.         {
  20.    
  21.         isStartTimer = true;
  22.         Debug.Log("开始计时");
  23.         }
  24.     // Update is called once per frame
  25.     void Update()
  26.     {
  27.    
  28.                 if (isStartTimer)
  29.         {
  30.    
  31.             timer += Time.deltaTime;
  32.             Debug.Log("计时中:"+(int)timer);
  33.             if(timer >= totalTime)
  34.                         {
  35.    
  36.                 Debug.Log("结束计时:"+(int)timer);
  37.                 isStartTimer = false;
  38.                 timer = 0;
  39.             }
  40.                 }
  41.     }
  42. }
复制代码
演示效果:

2.第二种计时器Time.time

Time.time为从游戏运行开始到现在的时间,该方法一样寻常用作减法计时,原理是先记录一下按钮按下时的那一刹时的时间,再用当前时间减去记录的时间,大于计时时间时关闭,也是依赖Unity中Update方法的帧实行,可根据实际使用环境进行加减,以下给出减法利用。
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TimeTest2 : MonoBehaviour
  6. {
  7.    
  8.     float totalTime = 3;
  9.     float recordTime = 0;
  10.     public Button button;
  11.     bool isStartTimer = false
复制代码
来源:https://blog.csdn.net/weixin_45724919/article/details/126402345
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则