Fade.cs 986 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. public class Fade : MonoBehaviour
  5. {
  6. [SerializeField]
  7. private float fadeTime = 0.5f;
  8. private Image image;
  9. private Color color;
  10. private void Awake()
  11. {
  12. image = GetComponent<Image>();
  13. color = image.color;
  14. }
  15. public IEnumerator FadeIn()
  16. {
  17. float t = 0;
  18. while (t < fadeTime)
  19. {
  20. color.a = Mathf.Lerp(1.0f, 0.0f, t / fadeTime);
  21. image.color = color;
  22. t += Time.deltaTime;
  23. yield return null;
  24. }
  25. color.a = 0.0f;
  26. image.color = color;
  27. }
  28. public IEnumerator FadeOut()
  29. {
  30. float t = 0;
  31. while (t < fadeTime)
  32. {
  33. color.a = Mathf.Lerp(0.0f, 1.0f, t / fadeTime);
  34. image.color = color;
  35. t += Time.deltaTime;
  36. yield return null;
  37. }
  38. color.a = 1.0f;
  39. image.color = color;
  40. }
  41. }