Created a base CanvasGroupFader component to handle GUI object fading.
[VesselSimulator.git] / KerbalEngineer.Unity / CanvasGroupFader.cs
blob:a/KerbalEngineer.Unity/CanvasGroupFader.cs -> blob:b/KerbalEngineer.Unity/CanvasGroupFader.cs
--- a/KerbalEngineer.Unity/CanvasGroupFader.cs
+++ b/KerbalEngineer.Unity/CanvasGroupFader.cs
@@ -10,17 +10,25 @@
         private CanvasGroup m_CanvasGroup;
         private IEnumerator m_FadeCoroutine;
 
+        public bool fading
+        {
+            get
+            {
+                return m_FadeCoroutine != null;
+            }
+        }
+
         /// <summary>
-        ///     Fades the canvas group to a specified alpha value with optional callback.
+        ///     Fades the canvas group to a specified alpha using the supplied blocking state during fade with optional callback.
         /// </summary>
-        public void FadeTo(float alpha, Action callback = null)
+        public void FadeTo(float alpha, float duration, Action callback = null)
         {
-            if (m_CanvasGroup == null || gameObject.activeInHierarchy == false)
+            if (m_CanvasGroup == null)
             {
                 return;
             }
 
-            Fade(m_CanvasGroup.alpha, alpha, callback);
+            Fade(m_CanvasGroup.alpha, alpha, duration, callback);
         }
 
         /// <summary>
@@ -35,7 +43,6 @@
 
             alpha = Mathf.Clamp01(alpha);
             m_CanvasGroup.alpha = alpha;
-            m_CanvasGroup.interactable = !(alpha < 1.0f);
         }
 
         protected virtual void Awake()
@@ -47,32 +54,35 @@
         /// <summary>
         ///     Starts a fade from one alpha value to another with callback.
         /// </summary>
-        private void Fade(float from, float to, Action callback)
+        private void Fade(float from, float to, float duration, Action callback)
         {
             if (m_FadeCoroutine != null)
             {
                 StopCoroutine(m_FadeCoroutine);
             }
 
-            m_FadeCoroutine = FadeCoroutine(from, to, callback);
+            m_FadeCoroutine = FadeCoroutine(from, to, duration, callback);
             StartCoroutine(m_FadeCoroutine);
         }
 
         /// <summary>
         ///     Coroutine that handles the fading.
         /// </summary>
-        private IEnumerator FadeCoroutine(float from, float to, Action callback)
+        private IEnumerator FadeCoroutine(float from, float to, float duration, Action callback)
         {
             float progress = 0.0f;
 
             while (progress <= 1.0f)
             {
-                progress += Time.deltaTime;
+                progress += Time.deltaTime / duration;
                 SetAlpha(Mathf.Lerp(from, to, progress));
                 yield return null;
             }
 
+            print(m_CanvasGroup.alpha);
             callback?.Invoke();
+
+            m_FadeCoroutine = null;
         }
     }
 }