300x250

게임을 만들다 보면 퍼즈상태를 구현 하기 위해서 Time.timeScale = 0 을 사용해서 손쉽게 구현 할 수 있어요.

 

 

 

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

public class JeongTest2Main : MonoBehaviour
{
    public Text textTime;
    public Button btnPause;
    private float currentTime = 0;
    void Start()
    {        
        this.btnPause.onClick.AddListener(() =>
        {
            Time.timeScale = 0;
        });

        StartCoroutine(this.TimerRoutine());
    }

    private IEnumerator TimerRoutine()
    {
        while (true)
        {
            currentTime += Time.deltaTime;
            textTime.text = currentTime.ToString();
            yield return null;
        }        
    }
}

 

근데 이렇게 하면 게임 내에 있는 모든 시간이 멈춰 버려서 예를 들면 5초만 멈추기 같은 기능을 Time.deltaTime으론 구하기 힘들어져요. 그래서 유니티에서 제공하는게 아닌 C#에서 지원하는 System.Timers를 사용해서 구현하면 쉽게 할 수 있어요.

 

using System.Collections;
using System.Timers;
using UnityEngine;
using UnityEngine.UI;

public class JeongTest2Main : MonoBehaviour
{
    public Text textTime;
    public Button btnPause;
    private Timer timer;
    private float delta = 0;
    private float currentTime = 0;
    void Start()
    {        
        this.btnPause.onClick.AddListener(() =>
        {
            MyTimer();
            Time.timeScale = 0;
        });

        StartCoroutine(this.TimerRoutine());
    }

    private void MyTimer()
    {
        timer = new Timer();
        timer.Start();
        // 밀리세컨드 단위 1000 = 1초
        timer.Interval = 1000;

        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);  //주기마다 실행되는 이벤트 등록
    }

    private IEnumerator TimerRoutine()
    {
        while (true)
        {
            currentTime += Time.deltaTime;
            textTime.text = currentTime.ToString();
            yield return null;

            if (delta >= 5)
            {
                delta = 0;
                Time.timeScale = 1;
                timer.Stop();
                timer.Dispose();
            }
        }        
    }

    delegate void TimerEventFiredDelegate();
    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // 1초에 1씩증가
        delta += 1;
    }
}
300x250