Unity3D制作简易倒计时

方法一 :协程

在Unity3D场景中新建两个text,然后建个空物体,将倒计时脚本挂在空物体上。

using System;
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
public class CountDownTime : MonoBehaviour
{
    public GameObject second;
    public GameObject minute;
    public int second_time = 30;
    public int minute_time = 3;

    void Start()
    {
        StartCoroutine(Time());
    }
    /// <summary>
    /// 协程
    /// </summary>
    /// <returns></returns>
    IEnumerator Time()
    {
        while (second_time >= 0)
        {
            second.GetComponent<Text>().text = second_time.ToString();
            minute.GetComponent<Text>().text = minute_time.ToString();
            yield return new WaitForSeconds(1);
            second_time--;
            if(second_time == 0 && minute_time != 0)
            {
                minute_time--;
                second_time = 60;
            }else if (second_time == 0 && minute_time == 0)
            {
                Messagebox.MessageBox(IntPtr.Zero, "时间到了!", "提示弹窗", 0);
            }
        } 
    }
    /// <summary>
    /// 弹窗
    /// </summary>
    public class Messagebox
    {
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);
    }
}

然后将两个text放到脚本对应的位置上。

结果展示:

方法二:OnGUI

建一个空物体直接在上面挂脚本

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

public class DownTime : MonoBehaviour
{
    private Rect windowRect0 = new Rect(320, 20, 500, 360);
    public float minute;
    public float second;
    private int k = 0;
    private float lastTime;
    private float thisTime;

    public void OnGUI()
    {
        thisTime = Time.time;

        if (minute > 0 && second - 0 < 1e-8)
        {
            --minute;
            second = 60;
            ++k;
        }

        if (minute > 0 || second > 0)
        {

            GUI.Label(new Rect(200, 100, 500, 500), second.ToString());
            GUI.Label(new Rect(200, 800, 500, 500), minute.ToString());
            second -= thisTime - lastTime;
        }
        else
        {
            GUI.Window(0, windowRect0, DoMyWindow, "提示窗口");
            GUI.Label(new Rect(200, 100, 500, 500), "0");
            GUI.Label(new Rect(200, 800, 500, 500), "0");
        }

        lastTime = thisTime;
    }

    public void DoMyWindow(int windowId)
    {
        GUI.DragWindow(new Rect(0, 0, 500, 360));
        GUI.Label(new Rect(200, 30, 160, 150), "时间到了");
    }
}

输入分秒直接运行即可

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值