Countdown Timer-tutorial voor Unity

Een countdown timer is een virtuele klok die vanaf een ingestelde tijd tot 0 telt.

Om een ​​afteltimer te maken in Unity, moet je een script maken dat de hoeveelheid afteltijd opslaat en deze om 00:00 uur weergeeft. formaat.

Unity afteltimer in de linkerbovenhoek.

De timer bevat deze formaten:

  • Dagen:Uren:Minuten:Seconden:Milliseconden
  • Uren: Minuten: Seconden: Milliseconden
  • Minuten: Seconden: Milliseconden
  • Seconden: milliseconden
  • Plus al het bovenstaande, maar zonder milliseconden

Stappen

Volg de onderstaande stappen om een ​​afteltimer te maken in Unity:

  • Maak een nieuw script, noem het 'SC_CountdownTimer', verwijder alles ervan en plak de onderstaande code:
  • Het script voor de afteltimer C# trekt af van de totale waarde tot 0 wordt bereikt en past de opgemaakte tijd toe op een tekstelement.

SC_CountdownTimer.cs

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

public class SC_CountdownTimer : MonoBehaviour
{
    public enum CountdownFormatting { DaysHoursMinutesSeconds, HoursMinutesSeconds, MinutesSeconds, Seconds };
    public CountdownFormatting countdownFormatting = CountdownFormatting.MinutesSeconds; //Controls the way the timer string will be formatted
    public bool showMilliseconds = true; //Whether to show milliseconds in countdown formatting
    public double countdownTime = 600; //Countdown time in seconds

    Text countdownText;
    double countdownInternal;
    bool countdownOver = false;

    // Start is called before the first frame update
    void Start()
    {
        countdownText = GetComponent<Text>();
        countdownInternal = countdownTime; //Initialize countdown
    }

    void FixedUpdate()
    {
        if (countdownInternal > 0)
        {
            countdownInternal -= Time.deltaTime;

            //Clamp the timer value so it never goes below 0
            if (countdownInternal < 0)
            {
                countdownInternal = 0;
            }

            countdownText.text = FormatTime(countdownInternal, countdownFormatting, showMilliseconds);
        }
        else
        {
            if (!countdownOver)
            {
                countdownOver = true;

                Debug.Log("Countdown has finished running...");

                //Your code here...
            }
        }
    }

    string FormatTime(double time, CountdownFormatting formatting, bool includeMilliseconds)
    {
        string timeText = "";

        int intTime = (int)time;
        int days = intTime / 86400;
        int hoursTotal = intTime / 3600;
        int hoursFormatted = hoursTotal % 24;
        int minutesTotal = intTime / 60;
        int minutesFormatted = minutesTotal % 60;
        int secondsTotal = intTime;
        int secondsFormatted = intTime % 60;
        int milliseconds = (int)(time * 100);
        milliseconds = milliseconds % 100;

        if (includeMilliseconds)
        {
            if (formatting == CountdownFormatting.DaysHoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}:{4:00}", days, hoursFormatted, minutesFormatted, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.HoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", hoursTotal, minutesFormatted, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.MinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}", minutesTotal, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.Seconds)
            {
                timeText = string.Format("{0:00}:{1:00}", secondsTotal, milliseconds);
            }
        }
        else
        {
            if (formatting == CountdownFormatting.DaysHoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", days, hoursFormatted, minutesFormatted, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.HoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}", hoursTotal, minutesFormatted, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.MinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}", minutesTotal, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.Seconds)
            {
                timeText = string.Format("{0:00}", secondsTotal);
            }
        }

        return timeText;
    }
}
  • Maak een nieuwe UI-tekst door met de rechtermuisknop op de Hiërarchieweergave -> UI -> Tekst te klikken en deze een naam te geven 'Countdown'

Unity maakt nieuwe UI-tekst

  • Wijzig 'Countdown' Rect Transformeer de uitlijning naar linksboven, draai naar (0, 1), Pos X en Pos Y naar 5, Breedte naar 300 en Hoogte naar 60

  • Wijzig de 'Countdown' tekstlettertypestijl in vet, lettergrootte in 34, uitlijning in links midden en kleur in wit

Unity Text Component Inspector Arial Bold Lettergrootte 34

  • Koppel het SC_CountdownTimer-script aan het 'Countdown'-object dat een tekstcomponent heeft.

Je zult merken dat het script een paar variabelen heeft:

  • Countdown-opmaak bepaalt welke tijdseenheden worden opgenomen in de tekenreeksopmaak.
  • Milliseconden weergeven bepaalt of het aantal milliseconden moet worden weergegeven.
  • Afteltijd is de duur van het aftellen in seconden, de waarde 600 komt bijvoorbeeld overeen met 10 minuten.

Nadat u op Afspelen heeft gedrukt, ziet u de tekst met een afteltimer:

Na 0 seconden zal het script een regel in de console afdrukken, wat aangeeft dat het aftellen is voltooid. Gebruik dat deel van het script om uw eigen functionaliteit toe te voegen.