FadeInOut.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace Mirror.Examples.AdditiveLevels
  5. {
  6. public class FadeInOut : MonoBehaviour
  7. {
  8. // set these in the inspector
  9. [Tooltip("Reference to Image component on child panel")]
  10. public Image fadeImage;
  11. [Tooltip("Color to use during scene transition")]
  12. public Color fadeColor = Color.black;
  13. [Range(1, 100), Tooltip("Rate of fade in / out: higher is faster")]
  14. public byte stepRate = 2;
  15. float step;
  16. void OnValidate()
  17. {
  18. if (fadeImage == null)
  19. fadeImage = GetComponentInChildren<Image>();
  20. }
  21. void Start()
  22. {
  23. // Convert user-friendly setting value to working value
  24. step = stepRate * 0.001f;
  25. }
  26. /// <summary>
  27. /// Calculates FadeIn / FadeOut time.
  28. /// </summary>
  29. /// <returns>Duration in seconds</returns>
  30. public float GetDuration()
  31. {
  32. float frames = 1 / step;
  33. float frameRate = Time.deltaTime;
  34. float duration = frames * frameRate * 0.1f;
  35. return duration;
  36. }
  37. public IEnumerator FadeIn()
  38. {
  39. float alpha = fadeImage.color.a;
  40. while (alpha < 1)
  41. {
  42. yield return null;
  43. alpha += step;
  44. fadeColor.a = alpha;
  45. fadeImage.color = fadeColor;
  46. }
  47. }
  48. public IEnumerator FadeOut()
  49. {
  50. float alpha = fadeImage.color.a;
  51. while (alpha > 0)
  52. {
  53. yield return null;
  54. alpha -= step;
  55. fadeColor.a = alpha;
  56. fadeImage.color = fadeColor;
  57. }
  58. }
  59. }
  60. }