Unity开发小技巧(一)、计时器Timer

这篇具有很好参考价值的文章主要介绍了Unity开发小技巧(一)、计时器Timer。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.第一种计时器Time.deltaTime

Time.deltaTime为游戏每帧执行的时间,该方法一般用加法来计时,原理是利用nity中Update方法的每帧执行的时间,按钮按下后不断累加,大于计时时间时关闭,可根据实际使用情况进行加减,以下给出加法操作。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeTest : MonoBehaviour
{
    float totalTime = 3;
    float timer = 0;
    bool isStartTimer = false;
    public Button button;
    // Start is called before the first frame update
    void Start()
    {
        button.onClick.AddListener(OnClickBtn);
    }

    private void OnClickBtn()
	{
        isStartTimer = true;
        Debug.Log("开始计时");
	}

    // Update is called once per frame
    void Update()
    {
		if (isStartTimer)
        {
            timer += Time.deltaTime;
            Debug.Log("计时中:"+(int)timer);
            if(timer >= totalTime)
			{
                Debug.Log("结束计时:"+(int)timer);
                isStartTimer = false;
                timer = 0;
            }
		}
    }
}

演示结果:
Unity开发小技巧(一)、计时器Timer

2.第二种计时器Time.time

Time.time为从游戏运行开始到现在的时间,该方法一般用作减法计时,原理是先记录一下按钮按下时的那一瞬间的时间,再用当前时间减去记录的时间,大于计时时间时关闭,也是依靠Unity中Update方法的帧执行,可根据实际使用情况进行加减,以下给出减法操作。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeTest2 : MonoBehaviour
{
    float totalTime = 3;
    float recordTime = 0;
    public Button button;
    bool isStartTimer = false;
    // Start is called before the first frame update
    void Start()
    {

        button.onClick.AddListener(OnClickBtn);
    }

    private void OnClickBtn()
	{
        Debug.Log("timer2开始计时");
        recordTime = Time.time;
        isStartTimer = true;
    }

    // Update is called once per frame
    void Update()
    {
		if (isStartTimer)
		{
            Debug.Log("timer2计时中:" + (int)(Time.time - recordTime));
            if(Time.time - recordTime >= totalTime)
			{
                Debug.Log("timer2结束计时:" + (int)(Time.time - recordTime));
                isStartTimer = false;
            }
        } 
    }
}

演示结果:
Unity开发小技巧(一)、计时器Timer

3.第三种计时器timer

该计时器为C#中依靠线程执行的计时器。我自己又封装了一下,大家可参考如下代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyTimer
{
    System.Timers.Timer timer;
    public MyTimer()
    {
        timer = new System.Timers.Timer();
        timer.Interval = 2000;
        timer.Elapsed += FinishTimer;
    }
    public MyTimer(double time)
    {
        timer = new System.Timers.Timer();
        timer.Interval = time;
        timer.Elapsed += FinishTimer;
    }

    public void Start()
    {
        Debug.Log("开始");
        timer.Start();
    }

    public void Stop()
    {
        timer.Stop();
    }

    public void FinishTimer(object sender, System.Timers.ElapsedEventArgs e)
    {
        Debug.Log(sender.ToString());
        Debug.Log("timer3:完成计时:" + e.SignalTime.ToLocalTime());
        timer.Stop();
    }
}

演示结果:
Unity开发小技巧(一)、计时器Timer

区别

第一种和第二种需要放在主线程(Update方法)中执行,第三种为另外分一个线程执行起到了分担主线程的作用。但各有各的好处,在第三种方法中不能直接调用GameObject,Instantiate,(UI中)Text等对象或方法,如果涉及文本框数字的实时显示,推荐使用一,二种方法;如果只是需要计时后调用一次的,如按钮的长按等,可设置bool开关并结合主线程控制,用来分担主线程压力。在profile性能分析器中可明显的观测到第一种方法和第二种方法有在计时的时候有明显的波峰出现,而第三种方法只在按钮点击的瞬间有明显的波峰显示,大家可结合性能分析profile来观察,得出结论。

4.第四种计时器Invoke

Unity中Mono提供了Invoke(“methodName”,time)方法,其作用是多长时间执行该方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InvokeTimer : MonoBehaviour
{
    public float time = 3.5f;
    private int index = 0;
    // Start is called before the first frame update
    void Start()
    {
        Timer(time);
    }

    void StartTimer()
    {
        index++;
        if (index > time)
        {
            Debug.Log(time);
            Debug.Log("完成计时");
            return;
        }
        Debug.Log(index);
    }

    private void Timer(float time)
    {
        if (time < 1)
        {
            Invoke("StartTimer", time);
            return;
        }
        
        for (int i = 1; i < time; i++)
        {
            Invoke("StartTimer", i);
        }
        Invoke("StartTimer", time);
    }
}

运行结果:
Unity开发小技巧(一)、计时器Timer

5.第五种计时器IEnumerator

利用协程的yield return new WaitForSeconds(float time),此方法既可以不占用主线程,又可以操控unity中的控件,如Text,GameObject等类。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class IEnumeratorTimer : MonoBehaviour
{
    public float time = 5.43f;
    public Text text;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(Timer(time));
    }

    IEnumerator Timer(float time)
    {
        for (int i = 1; i < time; i++)
        {
            yield return new WaitForSeconds(1);
            Debug.Log(i);
            text.text = i.ToString();
        }
        float remainTime = time - (int)time;
        if(remainTime != 0)
        {
            yield return new WaitForSeconds(remainTime);
            text.text = time.ToString();
            Debug.Log(time);
            Debug.Log("完成计时");
        }
    }
}

运行效果:
Unity开发小技巧(一)、计时器Timer

6.第六种计时器Thread

利用多线程的方式计时,缺点和第三种计时器一样

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.Events;

public class ThreadTimer : MonoBehaviour
{
    public float time = 7.52f;

    // Start is called before the first frame update
    void Start()
    {
        Thread thread = new Thread(StartTimer);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }

    private void StartTimer()
    {
        Timer(time, FinishTimer);
    }

    private void Timer(float time,UnityAction unity)
    {
        int remainTime = 0;//剩余时间
        if (time < 1)
        {
            remainTime = (int)(time * 1000);
            Thread.Sleep(remainTime);
            Debug.Log(time);
            return;
        }
        int count = (int)time;
        remainTime = (int)((time - count) * 1000);
        for (int i = 1; i < time; i++)
        {
            Thread.Sleep(1000);
            Debug.Log(i);
        }
        Thread.Sleep(remainTime);
        Debug.Log(time);
        unity();
    }

    public void FinishTimer()
    {
        Debug.Log("完成计时");
    }
}

运行结果:
Unity开发小技巧(一)、计时器Timer
大家可综合实际情况选择使用。文章来源地址https://www.toymoban.com/news/detail-456499.html

到了这里,关于Unity开发小技巧(一)、计时器Timer的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • unity工具类篇 unity 计时器

    在规定时间内倒计时 显示倒计时时间 显示正计时时间 暂停、继续 时间速率影响 获取倒计时剩余时间 倒计时结束的回调 参考链接:https://itmonon.blog.csdn.net/article/details/124827131?spm=1001.2014.3001.5502

    2024年02月13日
    浏览(26)
  • Unity_计时器实现的四种方式

    在Unity中,可以使用Time.deltaTime来计算游戏运行的时间。可以在每一帧的Update()函数中使用它,将它乘以一个时间因子,得到累计的时间。例如: 相信系统学习过Unity的人都听说过协程,使用协程可以轻而易举的来实现计时的操作 Unity中的InvokeRepeating函数可以在一定时间间隔内重

    2024年02月09日
    浏览(16)
  • 【Unity每日一记】Unity中的计时器——4种方法的实现

    👨‍💻个人主页 :@元宇宙-秩沅 👨‍💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅! 👨‍💻 本文由 秩沅 原创 👨‍💻 收录于专栏 : unity每日一记 ⭐【软件设计师高频考点暴击】 ⭐【Unityc#专题篇】之c#系统化大礼包】 ⭐【unity数据持久化】数据管理类_PlayerPrfs ⭐【u

    2024年02月06日
    浏览(9)
  • Unity快速入门教程-制作一个简易版的计时器Time.deltaTime

    制作游戏的时候,可能会需要到一个计时器,本篇文章附完整计时器代码 本文将简单介绍 一次计时器 和 循环计时器 的代码 Time.deltaTime是帧与帧相减出来的,即 Time.deltaTime=后一帧时间-前一帧时间 ,计算结果由你的电脑配置而定,不是固定值。由于Time.deltaTime的结果是由后一

    2024年02月12日
    浏览(14)
  • 14、计时器、定时器设计与应用

    掌握同步四位二进制计数器 74LS161 的工作原理和设计方法 掌握时钟/定时器的工作原理与设计方法 任务 1:采用行为描述设计同步四位二进制计数器 74LS161 任务 2:基于 74LS161 设计时钟应用 1.创建工程并创建 Verilog 文件 建立 HDL 类型的工程 My74LS161,创建 Verilog 文件 My74LS161,

    2024年02月03日
    浏览(15)
  • 51单片机通过计时器实现倒计时

    软件 : Keil5+Proteus7 元件 : AT89C51 * 1,7SEG-MPX2-CA * 1

    2024年02月16日
    浏览(22)
  • RIP四大计时器

    RIP 计时器(以下均以华为 ensp 中信息为参考) 希望有需要的小伙伴可以参考参考,如有误解、请指正! 一、实验原理 1. 更新计时器( Update Timer ) Update time(更新时间):指运行RIP协议的路由器向其连接口广播自己的路由信息的时间间隔(用于更新RIP路由表信息),控制

    2024年02月03日
    浏览(13)
  • 555计时器原理

    以Multisim上的555计时器为例: 图0.0 555计时器包含八个引脚 分别为: RST - Reset 复位引脚(低电平有效) DIS - Discharge 三极管集电极Collector输入引脚 THR - Threshold 上阈值电压引脚 TRI - Trigger 触发引脚 CON - Control voltage 1 电压控制引脚 OUT - Output 信号输出引脚 VCC GND 555定时器内部功能图

    2024年02月05日
    浏览(16)
  • WPF计时器功能

    本文实现WPF的计时器功能是通过system.timers.timer这个组件实现的。现在网上相关的资料有很多,我只是在自己的工作中刚好遇到要实现这个功能,中间也走了很多的弯路,不停的参考网上现有的资源,终于实现了基本的定时功能。希望本文可以帮助到您,让您花更少的时间来完

    2024年02月05日
    浏览(20)
  • 24秒计时器

    方案一:采用计数器(74LS192)作为核心部分。同时选择(74LS47)作为BCD码译码器来对7段数码显示管进行译码驱动,两个七段共阳数码显示管进行显示。采用计时器(NE555)制成的多谐振荡器,进行秒脉冲的输入。因为我们需要对其进行暂停、清零、报警和自动清零等控制,所

    2024年02月06日
    浏览(20)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包