| | | 1 | | using System.Collections; |
| | | 2 | | using UnityEngine; |
| | | 3 | | |
| | | 4 | | /// <summary> |
| | | 5 | | /// Fades a canvas over time using a coroutine and a canvas group |
| | | 6 | | /// </summary> |
| | | 7 | | [RequireComponent(typeof(CanvasGroup))] |
| | | 8 | | public class FadeCanvas : MonoBehaviour |
| | | 9 | | { |
| | | 10 | | [Tooltip("The speed at which the canvas fades")] |
| | 2 | 11 | | public float defaultDuration = 1.0f; |
| | | 12 | | |
| | 3 | 13 | | public Coroutine CurrentRoutine { private set; get; } = null; |
| | | 14 | | |
| | 2 | 15 | | private CanvasGroup canvasGroup = null; |
| | 2 | 16 | | private float alpha = 0.0f; |
| | | 17 | | |
| | 2 | 18 | | private float quickFadeDuration = 0.25f; |
| | | 19 | | |
| | | 20 | | private void Awake() |
| | 1 | 21 | | { |
| | 1 | 22 | | canvasGroup = GetComponent<CanvasGroup>(); |
| | 1 | 23 | | } |
| | | 24 | | |
| | | 25 | | public void StartFadeIn() |
| | 0 | 26 | | { |
| | 0 | 27 | | StopAllCoroutines(); |
| | 0 | 28 | | CurrentRoutine = StartCoroutine(FadeIn(defaultDuration)); |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | public void StartFadeOut() |
| | 1 | 32 | | { |
| | 1 | 33 | | StopAllCoroutines(); |
| | 1 | 34 | | CurrentRoutine = StartCoroutine(FadeOut(defaultDuration)); |
| | 1 | 35 | | } |
| | | 36 | | |
| | | 37 | | public void QuickFadeIn() |
| | 0 | 38 | | { |
| | 0 | 39 | | StopAllCoroutines(); |
| | 0 | 40 | | CurrentRoutine = StartCoroutine(FadeIn(quickFadeDuration)); |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | public void QuickFadeOut() |
| | 0 | 44 | | { |
| | 0 | 45 | | StopAllCoroutines(); |
| | 0 | 46 | | CurrentRoutine = StartCoroutine(FadeOut(quickFadeDuration)); |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | private IEnumerator FadeIn(float duration) |
| | 0 | 50 | | { |
| | 0 | 51 | | float elapsedTime = 0.0f; |
| | | 52 | | |
| | 0 | 53 | | while (alpha <= 1.0f) |
| | 0 | 54 | | { |
| | 0 | 55 | | SetAlpha(elapsedTime / duration); |
| | 0 | 56 | | elapsedTime += Time.deltaTime; |
| | 0 | 57 | | yield return null; |
| | 0 | 58 | | } |
| | 0 | 59 | | } |
| | | 60 | | |
| | | 61 | | private IEnumerator FadeOut(float duration) |
| | 1 | 62 | | { |
| | 1 | 63 | | float elapsedTime = 0.0f; |
| | | 64 | | |
| | 6 | 65 | | while (alpha >= 0.0f) |
| | 5 | 66 | | { |
| | 5 | 67 | | SetAlpha(1 - (elapsedTime / duration)); |
| | 5 | 68 | | elapsedTime += Time.deltaTime; |
| | 5 | 69 | | yield return null; |
| | 5 | 70 | | } |
| | 1 | 71 | | } |
| | | 72 | | |
| | | 73 | | private void SetAlpha(float value) |
| | 5 | 74 | | { |
| | 5 | 75 | | alpha = value; |
| | 5 | 76 | | canvasGroup.alpha = alpha; |
| | 5 | 77 | | } |
| | | 78 | | } |