mirror of
https://github.com/Earth-Genesis-Games/Carrasco.git
synced 2026-09-11 09:52:19 +00:00
99 lines
2.5 KiB
C#
99 lines
2.5 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using UnityEngine.Events;
|
|
using System.Collections;
|
|
|
|
[RequireComponent(typeof(Slider))]
|
|
public class CountdownSliderRealtime : MonoBehaviour
|
|
{
|
|
[Header("Config")]
|
|
[Min(0.01f)] public float countdownSeconds = 5f;
|
|
public bool autoStartOnEnable = true;
|
|
public GameObject destroyTarget; // Si es null, se destruye este GameObject
|
|
|
|
[Header("Refs")]
|
|
public Slider slider; // Si es null, se busca en este GO o en hijos
|
|
|
|
[Header("Events")]
|
|
public UnityEvent onCountdownFinished; // Opcional: acciones al terminar
|
|
|
|
private Coroutine running;
|
|
|
|
void Awake()
|
|
{
|
|
if (slider == null)
|
|
{
|
|
slider = GetComponent<Slider>();
|
|
if (slider == null)
|
|
slider = GetComponentInChildren<Slider>(true);
|
|
}
|
|
|
|
if (destroyTarget == null)
|
|
destroyTarget = gameObject;
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
if (slider == null)
|
|
{
|
|
Debug.LogError("[CountdownSliderRealtime] No se encontró Slider.");
|
|
return;
|
|
}
|
|
|
|
slider.maxValue = countdownSeconds;
|
|
slider.value = countdownSeconds;
|
|
|
|
if (autoStartOnEnable)
|
|
StartCountdown(countdownSeconds);
|
|
}
|
|
|
|
void OnDisable()
|
|
{
|
|
if (running != null)
|
|
{
|
|
StopCoroutine(running);
|
|
running = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Inicia o reinicia el conteo con los segundos indicados (tiempo real).
|
|
/// </summary>
|
|
public void StartCountdown(float seconds)
|
|
{
|
|
countdownSeconds = Mathf.Max(0.01f, seconds);
|
|
if (running != null) StopCoroutine(running);
|
|
running = StartCoroutine(CountdownRoutine(countdownSeconds));
|
|
}
|
|
|
|
private IEnumerator CountdownRoutine(float seconds)
|
|
{
|
|
float endTime = Time.realtimeSinceStartup + seconds;
|
|
|
|
// Asegurar valores iniciales
|
|
slider.maxValue = seconds;
|
|
slider.value = seconds;
|
|
|
|
while (true)
|
|
{
|
|
float remaining = endTime - Time.realtimeSinceStartup;
|
|
if (remaining <= 0f) break;
|
|
|
|
slider.value = remaining;
|
|
yield return null; // Actualiza cada frame, independiente de timeScale
|
|
}
|
|
|
|
slider.value = 0f;
|
|
|
|
// Evento al terminar
|
|
if (onCountdownFinished != null)
|
|
onCountdownFinished.Invoke();
|
|
|
|
// Destruir si corresponde
|
|
if (destroyTarget != null)
|
|
Destroy(destroyTarget);
|
|
|
|
running = null;
|
|
}
|
|
}
|