Fader.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Immersal.Samples.Util
  5. {
  6. [RequireComponent(typeof(UnityEngine.CanvasGroup))]
  7. public class Fader : MonoBehaviour
  8. {
  9. public float fadeTime = 1f;
  10. private IEnumerator m_fade;
  11. private CanvasGroup m_canvasGroup;
  12. void Start()
  13. {
  14. }
  15. void OnEnable()
  16. {
  17. m_canvasGroup = GetComponent<CanvasGroup>();
  18. }
  19. public void ToggleFade(bool isOn)
  20. {
  21. if (isOn)
  22. FadeIn();
  23. else
  24. FadeOut();
  25. }
  26. public void FadeOut()
  27. {
  28. if (m_fade != null)
  29. {
  30. StopCoroutine(m_fade);
  31. }
  32. if (!gameObject.activeInHierarchy)
  33. return;
  34. else
  35. m_canvasGroup.alpha = 1f;
  36. m_fade = FadeOutCoroutine();
  37. StartCoroutine(m_fade);
  38. }
  39. public void FadeIn()
  40. {
  41. if (m_fade != null)
  42. {
  43. StopCoroutine(m_fade);
  44. }
  45. if (!gameObject.activeInHierarchy)
  46. {
  47. gameObject.SetActive(true);
  48. m_canvasGroup.alpha = 0f;
  49. }
  50. m_fade = FadeInCoroutine();
  51. StartCoroutine(m_fade);
  52. }
  53. IEnumerator FadeOutCoroutine()
  54. {
  55. yield return new WaitForSeconds(0.1f);
  56. while (m_canvasGroup.alpha > 0)
  57. {
  58. m_canvasGroup.alpha -= Time.deltaTime / fadeTime;
  59. yield return null;
  60. }
  61. gameObject.SetActive(false);
  62. yield return null;
  63. }
  64. IEnumerator FadeInCoroutine()
  65. {
  66. yield return new WaitForSeconds(0.1f);
  67. while (m_canvasGroup.alpha < 1f)
  68. {
  69. m_canvasGroup.alpha += Time.deltaTime / fadeTime;
  70. yield return null;
  71. }
  72. m_canvasGroup.alpha = 1f;
  73. yield return null;
  74. }
  75. }
  76. }