栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity中实现倒计时的几种方式

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity中实现倒计时的几种方式

1. Time.time

using UnityEngine;

public class TimeTest : MonoBehaviour
{
    public float secound = 10;

    void Update()
    {
        Timing();
    }

    private float nextTime = 1;
    private void Timing()
    {
        if (secound <= 0) return;
        if(Time.time >= nextTime)
        {
            secound -= 1;
            Debug.Log(secound);
            nextTime = Time.time + 1;
        }
    }
}

2. Time.deltaTime

using UnityEngine;

public class TimeTest : MonoBehaviour
{
    public float secound = 10;

    void Update()
    {
        Timing();
    }

    private float waitTime;
    private void Timing()
    {
        if (secound <= 0) return;
        waitTime += Time.deltaTime;
        if(waitTime >=1)
        {
            secound--;
            Debug.Log(secound);
            waitTime = 0;
        }
    }
}

3. InvokeRepeating

using UnityEngine;

public class TimeTest : MonoBehaviour
{
    public float secound = 10;

    void Start() => InvokeRepeating("Timing", 1, 1);

    private void Timing()
    {
        if (secound <= 0) return;
        secound--;
        Debug.Log(secound);
    }
}

4. 协程

using System.Collections;
using UnityEngine;

public class TimeTest : MonoBehaviour
{
    public float secound = 10;

    IEnumerator Start() //将Start方法作为协同程序,则不必调用StartCoroutine
    {        
        while (secound > 0)
        {
            yield return new WaitForSeconds(1);
            secound--;
            Debug.Log(secound);
        }
    }
}

5. 线程

using System.Threading;
using UnityEngine;

public class TimeTest : MonoBehaviour
{
    public float secound = 10;

    void Start()
    {
        Thread thread = new Thread(Timing);
        thread.Start();
    }

    private void Timing()
    {
        while (secound > 0)
        {
            Thread.Sleep(1000);
            secound--;
            Debug.Log(secound);
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898075.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号