1
0

CountdownDisplay.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using TMPro;
  3. using UnityEngine;
  4. using Debug = System.Diagnostics.Debug;
  5. namespace Display
  6. {
  7. public class CountdownDisplay : MonoBehaviour
  8. {
  9. public int countdown = 3;
  10. public TextMeshProUGUI countdownText;
  11. public float distance;
  12. private Camera cam;
  13. private Transform camTransform;
  14. private Transform canvasTransform;
  15. public delegate string CountdownDoneCallback();
  16. public CountdownDoneCallback OnCountdownDone { get; set; }
  17. private float lastTime;
  18. private void Start()
  19. {
  20. cam = Camera.main;
  21. Debug.Assert(cam != null, nameof(cam) + " != null");
  22. camTransform = cam.transform;
  23. lastTime = Time.time;
  24. canvasTransform = GetComponentInChildren<Canvas>().transform;
  25. }
  26. private void Update()
  27. {
  28. var t = Time.time;
  29. if (t - lastTime >= 1)
  30. {
  31. lastTime = t;
  32. countdown--;
  33. countdownText.text = $"{countdown}";
  34. if (countdown == 0)
  35. {
  36. countdownText.text = OnCountdownDone?.Invoke();
  37. Destroy(gameObject, 0.5f);
  38. }
  39. }
  40. canvasTransform.SetPositionAndRotation(camTransform.position + camTransform.forward * distance,
  41. camTransform.rotation);
  42. }
  43. }
  44. }