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), "时间到了");
    }
}

输入分秒直接运行即可

 


版权声明:本文为weixin_53965540原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。