Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using System.Collections;
- public class TimerController : MonoBehaviour
- {
- private float _levelDuration; //you'd set this at the beginning of each level
- private Text timerText;
- private float startTime;
- private float currentTime;
- private bool timerActive;
- void Awake()
- {
- timerText = gameObject.GetComponent<Text>();
- if (timerText == null)
- {
- Debug.LogError("This script needs to be attached to a GUI text object!");
- this.enabled = false;
- return;
- }
- }
- void Update()
- {
- UpdateTimer();
- }
- public void SetTimer(float levelDuration)
- {
- _levelDuration = levelDuration;
- SetTimerString(levelDuration);
- }
- public void StartTimer()
- {
- timerActive = true;
- startTime = Time.time;
- }
- public void SetTimerActive(bool active)
- {
- timerActive = active;
- }
- void UpdateTimer()
- {
- if (!timerActive)
- return;
- float remainingTime = _levelDuration - (Time.time - startTime);
- if (remainingTime > 0.0f)
- {
- SetTimerString(remainingTime);
- }
- else
- {
- SetTimerString(0f);
- //do stuff here to trigger the end of the level
- //best to probably set a private variable in this class that can be read from another class via a method
- }
- }
- private void SetTimerString(float time)
- {
- //convert the time to the format you want to show - I'm not doing any formatting :P
- timerText.text = time.ToString();
- }
- public void AddToTimer(float time)
- {
- //either add to levelDuration or deduct from startTime doesn't matter - I choose deducting from the startTime because you might want to reference levelDUration later
- startTime += time;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement