Files
Test-Multiplayer/Assets/Scripts/UI/MenuFadeIn.cs
T

93 lines
2.4 KiB
C#

using System.Collections;
using UnityEngine;
[RequireComponent(typeof(CanvasGroup))]
public class MenuFadeIn : MonoBehaviour
{
public float delay = 0.3f;
public float duration = 3.5f;
CanvasGroup _group;
Coroutine _fadeRoutine;
bool _started;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void ReactivateFadeImages()
{
var fadeComponents = Resources.FindObjectsOfTypeAll<MenuFadeIn>();
foreach (var fadeComponent in fadeComponents)
{
if (!fadeComponent.gameObject.scene.IsValid())
continue;
fadeComponent.gameObject.SetActive(true);
}
}
void Awake()
{
// Ensure a CanvasGroup exists (SetupMainMenuScene adds one, but be defensive)
_group = GetComponent<CanvasGroup>();
if (_group == null) _group = gameObject.AddComponent<CanvasGroup>();
var canvas = GetComponentInParent<Canvas>();
if (canvas != null)
canvas.transform.localScale = Vector3.one;
_group.alpha = 1f;
_group.blocksRaycasts = true;
Debug.Log("[MenuFadeIn] Awake - CanvasGroup ensured, alpha=1");
}
void OnEnable()
{
if (_group == null) _group = GetComponent<CanvasGroup>() ?? gameObject.AddComponent<CanvasGroup>();
if (_started)
BeginFade();
}
void Start()
{
_started = true;
BeginFade();
}
void BeginFade()
{
_group.alpha = 1f;
_group.blocksRaycasts = true;
if (_fadeRoutine != null) StopCoroutine(_fadeRoutine);
_fadeRoutine = StartCoroutine(Fade());
Debug.Log("[MenuFadeIn] Starting fade (delay=" + delay + ", duration=" + duration + ")");
}
void OnDisable()
{
if (_fadeRoutine != null)
{
StopCoroutine(_fadeRoutine);
_fadeRoutine = null;
Debug.Log("[MenuFadeIn] OnDisable - stopped fade coroutine");
}
}
IEnumerator Fade()
{
if (delay > 0f) yield return new WaitForSecondsRealtime(delay);
float t = 0f;
while (t < duration)
{
t += Time.unscaledDeltaTime;
_group.alpha = 1f - Mathf.Clamp01(t / duration);
yield return null;
}
_group.alpha = 0f;
_group.blocksRaycasts = false;
Debug.Log("[MenuFadeIn] Fade finished");
}
}