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

Unity 制作倒计时

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

Unity 制作倒计时

效果:(按指定格式每秒倒计时,最后3秒倒计时变红)

步骤:

1.在Unity的Hierarchy面板点击鼠标右键->UI->Text,如下:

2.新建一个C#脚本,与上图中的TextTimer绑定,C#代码如下:

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


{
    private Text txtTimer;
    public float second;

    private void Start()
    {
        txtTimer = this.GetComponent();
    }

    private void Update()
    {

        if (second > 0)
        {
            second = second - Time.deltaTime;
            if (second / 60 < 1)
            {
                if (second < 4)
                {
                    txtTimer.color = Color.red;
                }
                txtTimer.text = string.Format("00:{0:d2}", (int)second % 60);
            }
            else
            {
                txtTimer.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);
            }
        }
        else
        {
            txtTimer.text = "00:00";
            txtTimer.color = Color.red;
        }
        
    }
}

或:(推荐)

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


public class CountdownTimer : MonoBehaviour
{
    private Text txtTimer;
    public float second;

    private void Start()
    {
        // 1.查找组件引用
        txtTimer = this.GetComponent();
        // 重复调用(被执行的方法名称,第一次执行时间,每次执行间隔时间)
        InvokeRepeating("Timer", 1, 1);
    }

    private void Timer()
    {
        second = second - 1;
        txtTimer.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);

        if (second <= 3) 
        {
            txtTimer.color = Color.red;
            if (second <= 0)
            {
                // 取消调用
                CancelInvoke("Timer");
            }
        }
    }
}

3.在Unity中运行即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898072.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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