數位時鐘及倒數計時(作業三)

倒數計時 code

新建腳本名稱:count_down

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

using UnityEngine.UI;
using System;

public class count_down : MonoBehaviour
{
    // Start is called before the first frame update
    private Text textclock;
    private float countdowntimerdelay;
    private float countdowntimerstarttime;
    public int input_sec;
    void Start()
    {
        textclock = GetComponent<Text>();
        //input_sec = 30;
        CountdownTimerRestet(input_sec);
    }

    // Update is called once per frame
    void Update()
    {
        string timermess = "countdown has \n finished";
        int timeleft = (int)CountdownTimersecre();
        if (timeleft > 0)
            timermess = "Countdown seconds \n remaining = " + LeadingZero(timeleft);
        textclock.text = timermess;
    }

    private void CountdownTimerRestet(float delaysec)
    {
        countdowntimerdelay = delaysec;
        countdowntimerstarttime = Time.time;
    }

    private float CountdownTimersecre()
    {
        float elapsedsec = Time.time - countdowntimerstarttime;
        float timeleft = countdowntimerdelay - elapsedsec;
        return timeleft;
    }
    private string LeadingZero(int n)
    {
        return n.ToString().PadLeft(2, '0');
    }
}

數位時鐘 code

新建腳本名稱:clock_digital

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

using UnityEngine.UI;
using System;

public class clock_digital : MonoBehaviour
{
    // Start is called before the first frame update
    private Text textclock;
    void Start()
    {
        textclock = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        DateTime time = DateTime.Now;
        string hour = LeadingZero(time.Hour);
        string minute = LeadingZero(time.Minute);
        string second = LeadingZero(time.Second);

        textclock.text = hour + ":" + minute + ":" + second;
    }

    private string LeadingZero(int n)
    {
        return n.ToString().PadLeft(2, '0');
    } 
}

洛克人圖

SHXJ
Latest posts by SHXJ (see all)

發佈留言