Countdown-Timer-Tutorial für Unity

Ein Countdown-Timer ist eine virtuelle Uhr, die von einer festgelegten Zeit bis 0 zählt.

Um einen Countdown-Timer in Unity zu erstellen, müssen Sie ein Skript erstellen, das die heruntergezählte Zeit speichert und im 00:00-Format anzeigt.

Unity-Countdown-Timer oben links.

Der Timer bietet folgende Formate:

  • Tage:Stunden:Minuten:Sekunden:Millisekunden
  • Stunden:Minuten:Sekunden:Millisekunden
  • Minuten:Sekunden:Millisekunden
  • Sekunden: Millisekunden
  • Plus alles oben Genannte, jedoch ohne Millisekunden

Schritte

Um einen Countdown-Timer in Unity zu erstellen, führen Sie die folgenden Schritte aus:

  • Erstellen ein neues Skript, nennen Sie es 'SC_CountdownTimer', entfernen Sie alles daraus und fügen Sie dann den folgenden Code ein:
  • Das Countdown-Timer-Skript C# subtrahiert vom Gesamtwert, bis es 0 erreicht, und wendet die formatierte Zeit auf ein Textelement an.

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;
    }
}
  • Erstellen Sie einen neuen UI-Text, indem Sie mit der rechten Maustaste auf die Hierarchieansicht -> UI -> Text klicken und ihn benennen 'Countdown'

Unity erstellt neuen UI-Text

  • Ändern Sie die 'Countdown' Rect Transform-Ausrichtung nach links oben, schwenken Sie auf (0, 1), Pos X und Pos Y auf 5, Breite auf 300 und Höhe auf 60

  • Ändern Sie den Textschriftstil 'Countdown' in Fett, die Schriftgröße auf 34, die Ausrichtung auf Links in der Mitte und die Farbe auf Weiß

Unity Text Component Inspector Arial Bold Schriftgröße 34

  • Hängen Sie das SC_CountdownTimer-Skript an das 'Countdown'-Objekt an, das über eine Textkomponente verfügt.

Sie werden feststellen, dass das Skript einige Variablen enthält:

  • Countdown-Formatierung steuert, welche Zeiteinheiten in die Zeichenfolgenformatierung einbezogen werden.
  • Show Milliseconds steuert, ob die Millisekundenzahl angezeigt werden soll.
  • Countdown Time ist die Dauer des Countdowns in Sekunden, der Wert 600 entspricht beispielsweise 10 Minuten.

Nachdem Sie Play gedrückt haben, sollten Sie den Text mit einem Countdown-Timer bemerken:

Bei 0 Sekunden gibt das Skript eine Zeile in der Konsole aus, die signalisiert, dass der Countdown abgelaufen ist. Verwenden Sie diesen Teil des Skripts, um Ihre eigene Funktionalität hinzuzufügen.

Empfohlene Artikel
FPC Swimmer – eine umfassende Einheit für immersive Wasserumgebungen
Maus-Look-Skript für Unity
Raycast- und projektilbasiertes Schießskript für Unity
So richten Sie den Joystick-Controller für die Bewegung in Unity ein
2D-Nahkampfangriff-Tutorial für Unity
Zone Controller Pro – Unity Asset Store-Paket
So verwenden Sie das neue HDRP-Wassersystem in Unity