ScreenFader.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace HQFPSWeapons.UserInterface
  5. {
  6. public class ScreenFader : UserInterfaceBehaviour
  7. {
  8. [SerializeField]
  9. private Image m_Image = null;
  10. [SerializeField]
  11. private float m_FadeSpeed = 0.3f;
  12. [SerializeField]
  13. private float m_FadePause = 1f;
  14. private float m_CurrentFadeSpeed = 1f;
  15. public override void OnPostAttachment()
  16. {
  17. Player.Death.AddListener(On_Death);
  18. Player.Respawn.AddListener(On_Respawn);
  19. m_Image.color = new Color(m_Image.color.r, m_Image.color.g, m_Image.color.b, 1f);
  20. StartCoroutine(C_FadeScreen(0f, m_FadePause));
  21. }
  22. private void On_Death()
  23. {
  24. StopAllCoroutines();
  25. StartCoroutine(C_FadeScreen(1f));
  26. }
  27. private void On_Respawn()
  28. {
  29. StopAllCoroutines();
  30. StartCoroutine(C_FadeScreen(0f, m_FadePause));
  31. }
  32. private IEnumerator C_FadeScreen(float targetAlpha, float pause = 0f)
  33. {
  34. m_CurrentFadeSpeed = 1f;
  35. yield return new WaitForSeconds(pause);
  36. while (Mathf.Abs(m_Image.color.a - targetAlpha) > 0f)
  37. {
  38. m_Image.color = MoveTowardsAlpha(m_Image.color, targetAlpha, Time.deltaTime * m_FadeSpeed * m_CurrentFadeSpeed);
  39. m_CurrentFadeSpeed += Time.deltaTime;
  40. yield return null;
  41. }
  42. }
  43. private Color MoveTowardsAlpha(Color color, float alpha, float maxDelta)
  44. {
  45. return new Color(color.r, color.g, color.b, Mathf.MoveTowards(color.a, alpha, maxDelta));
  46. }
  47. }
  48. }