Unity용 카운트다운 타이머 튜토리얼

카운트다운 타이머는 설정된 시간부터 0까지 카운트되는 가상 시계입니다.

Unity에서 카운트다운 타이머를 만들려면 카운트다운될 시간을 저장하고 이를 00:00 형식으로 표시하는 스크립트를 만들어야 합니다.

Unity 카운트다운 타이머 왼쪽 상단.

타이머에는 다음 형식이 포함됩니다.

  • 일:시:분:초:밀리초
  • 시:분:초:밀리초
  • 분:초:밀리초
  • 초:밀리초
  • 위의 모든 사항에 더해 밀리초는 제외됩니다.

단계

Unity에서 카운트다운 타이머를 만들려면 다음 단계를 따르세요.

  • 새 스크립트를 만들고 이름을 'SC_CountdownTimer'으로 지정하고 모든 내용을 제거한 후 아래 코드를 붙여넣습니다.
  • 카운트다운 타이머 C# 스크립트는 0에 도달할 때까지 총 값에서 빼고 형식이 지정된 시간을 텍스트 요소에 적용합니다.

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;
    }
}
  • 계층 보기 -> UI -> 텍스트를 마우스 오른쪽 버튼으로 클릭하고 이름을 지정하여 새 UI 텍스트를 만듭니다. 'Countdown'

Unity가 새 UI 텍스트를 생성합니다.

  • 'Countdown' Rect Transform 정렬을 왼쪽 상단으로 변경하고, 피벗을 (0, 1)로, Pos X 및 Pos Y를 5로, 너비를 300으로, 높이를 60으로 변경합니다.

  • 'Countdown' 텍스트 글꼴 스타일을 굵게, 글꼴 크기를 34로, 정렬을 왼쪽 가운데로, 색상을 흰색으로 변경합니다.

Unity 텍스트 구성 요소 검사기 Arial Bold 글꼴 크기 34

스크립트에 몇 가지 변수가 있음을 알 수 있습니다.

  • 카운트다운 형식은 문자열 형식에 포함될 시간 단위를 제어합니다.
  • Show Milliseconds은 밀리초 수를 표시할지 여부를 제어합니다.
  • 카운트다운 시간은 카운트다운 기간(초)입니다. 예를 들어 값 600은 10분에 해당합니다.

Play를 누르면 카운트다운 타이머가 표시된 텍스트가 표시됩니다.

0초에 스크립트는 콘솔에 라인을 인쇄하여 카운트다운이 완료되었음을 알리고 스크립트의 해당 부분을 사용하여 고유한 기능을 추가합니다.

추천 기사
Unity용 2D 근접 공격 튜토리얼
Unity 캡처 스크린샷 튜토리얼
Zone Controller Pro - Unity 에셋 스토어 패키지
Unity에서 새로운 HDRP 급수 시스템을 사용하는 방법
FPC Swimmer - 몰입형 수중 환경을 위한 포괄적인 Unity 에셋
Ultimate Spawner 2.0 - 판도를 바꾸는 자산
Unity용 마우스 보기 스크립트