// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using System.Collections; namespace PixelCrushers.DialogueSystem { /// /// Basic slider-based timer for response menus. /// [AddComponentMenu("")] // Use wrapper. public class UnityUITimer : MonoBehaviour { private UnityEngine.UI.Slider slider = null; private float startTime; // When the timer started. public virtual void Awake() { slider = GetComponent(); Tools.DeprecationWarning(this); } /// /// Called by the response menu. Starts the timer. Each tick, the UpdateTimeLeft /// method is called. /// /// Duration in seconds. /// Handler to invoke if the timer reaches zero. public virtual void StartCountdown(float duration, System.Action timeoutHandler) { StartCoroutine(Countdown(duration, timeoutHandler)); } private IEnumerator Countdown(float duration, System.Action timeoutHandler) { startTime = DialogueTime.time; float endTime = startTime + duration; while (DialogueTime.time < endTime) { float elapsed = DialogueTime.time - startTime; UpdateTimeLeft(Mathf.Clamp(1 - (elapsed / duration), 0, 1)); yield return null; } if (timeoutHandler != null) timeoutHandler(); } /// /// Adjusts the amount of time left. /// /// Seconds to fast-forward the timer (or rewind the timer if negative). public void SkipTime(float amountToSkip) { startTime -= amountToSkip; } /// /// Called each tick to update the timer display. The default method updates a UI slider. /// /// 1 at the start, 0 when the timer times out. public virtual void UpdateTimeLeft(float normalizedTimeLeft) { if (slider == null) return; slider.value = normalizedTimeLeft; } public virtual void OnDisable() { StopAllCoroutines(); } } }