FadeInOut.cs 1.78 KB
Newer Older
cann-alberto's avatar
cann-alberto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace Mirror.Examples.AdditiveLevels
{
    public class FadeInOut : MonoBehaviour
    {
        // set these in the inspector
        [Tooltip("Reference to Image component on child panel")]
        public Image fadeImage;

        [Tooltip("Color to use during scene transition")]
        public Color fadeColor = Color.black;

        [Range(1, 100), Tooltip("Rate of fade in / out: higher is faster")]
        public byte stepRate = 2;

        float step;

        void OnValidate()
        {
            if (fadeImage == null)
                fadeImage = GetComponentInChildren<Image>();
        }

        void Start()
        {
            // Convert user-friendly setting value to working value
            step = stepRate * 0.001f;
        }

        /// <summary>
        /// Calculates FadeIn / FadeOut time.
        /// </summary>
        /// <returns>Duration in seconds</returns>
        public float GetDuration()
        {
            float frames = 1 / step;
            float frameRate = Time.deltaTime;
            float duration = frames * frameRate * 0.1f;
            return duration;
        }

        public IEnumerator FadeIn()
        {
            float alpha = fadeImage.color.a;

            while (alpha < 1)
            {
                yield return null;
                alpha += step;
                fadeColor.a = alpha;
                fadeImage.color = fadeColor;
            }
        }

        public IEnumerator FadeOut()
        {
            float alpha = fadeImage.color.a;

            while (alpha > 0)
            {
                yield return null;
                alpha -= step;
                fadeColor.a = alpha;
                fadeImage.color = fadeColor;
            }
        }
    }
}