Created
July 8, 2024 08:23
-
-
Save Trissiklikk/536807a0931ac92a1065ee45b62c1633 to your computer and use it in GitHub Desktop.
UICanvasGroup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using UnityEngine; | |
using UnityEngine.EventSystems; | |
namespace Game.UI | |
{ | |
[RequireComponent(typeof(CanvasGroup))] | |
public abstract class UICanvasGroup : UIBehaviour | |
{ | |
[SerializeField] | |
protected CanvasGroup m_canvasGroup = default; | |
/// <summary> | |
/// Get the canvas group. | |
/// </summary> | |
public CanvasGroup CanvasGroup => m_canvasGroup; | |
[SerializeField] | |
protected float m_fadeDuration = default; | |
protected Coroutine m_fadeCoroutine; | |
/// <summary> | |
/// Method called when the UI is show. | |
/// </summary> | |
public virtual void Show(Action onCompleted = null) | |
{ | |
if (m_fadeCoroutine != null) | |
{ | |
StopCoroutine(m_fadeCoroutine); | |
m_fadeCoroutine = null; | |
} | |
m_fadeCoroutine = StartCoroutine(FadeIn(onCompleted)); | |
} | |
/// <summary> | |
/// Method called when the UI is hidden. | |
/// </summary> | |
public virtual void Hide(Action onCompleted = null) | |
{ | |
if (m_fadeCoroutine != null) | |
{ | |
StopCoroutine(m_fadeCoroutine); | |
m_fadeCoroutine = null; | |
} | |
m_fadeCoroutine = StartCoroutine(FadeOut(onCompleted)); | |
} | |
/// <summary> | |
/// Initialize the UI. | |
/// </summary> | |
protected virtual void Initialize() { } | |
/// <summary> | |
/// Method called fade in the UI. | |
/// </summary> | |
/// <returns></returns> | |
private IEnumerator FadeIn(Action onCompleted = null) | |
{ | |
while (m_canvasGroup.alpha < 1f) | |
{ | |
m_canvasGroup.alpha += Time.deltaTime / m_fadeDuration; | |
yield return null; | |
} | |
onCompleted?.Invoke(); | |
yield return null; | |
} | |
/// <summary> | |
/// Method called fade out the UI. | |
/// </summary> | |
/// <returns></returns> | |
private IEnumerator FadeOut(Action onCompleted = null) | |
{ | |
while (m_canvasGroup.alpha > 0f) | |
{ | |
m_canvasGroup.alpha -= Time.deltaTime / m_fadeDuration; | |
yield return null; | |
} | |
onCompleted?.Invoke(); | |
yield return null; | |
} | |
#if UNITY_EDITOR | |
protected override void OnValidate() | |
{ | |
base.OnValidate(); | |
m_canvasGroup ??= GetComponent<CanvasGroup>(); | |
} | |
protected override void Reset() | |
{ | |
base.Reset(); | |
m_canvasGroup = GetComponent<CanvasGroup>(); | |
} | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment