You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
HighGroundRoyaleNetcode/Assets/Scripts/SynchronizedTimer.cs

89 lines
1.9 KiB
C#

using System;
using Unity.Netcode;
using TMPro;
using UnityEngine;
public class SynchronizedTimer : NetworkBehaviour
{
public event Action OnTimerEnd;
[SerializeField] private TextMeshProUGUI timerText;
private NetworkVariable<float> timer = new NetworkVariable<float>(
0f,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Server
);
private bool isTimerRunning = false;
private void Start()
{
timerText.gameObject.SetActive( false );
}
private void Update()
{
if (IsServer && isTimerRunning)
{
timer.Value -= Time.deltaTime;
if (timer.Value <= 0)
{
timer.Value = 0;
isTimerRunning = false;
OnTimerEnd?.Invoke();
}
UpdateTimerUI();
}
}
public void StartTimerServer(float time)
{
if (!isTimerRunning && time > 0)
{
timer.Value = time;
isTimerRunning = true;
timerTextEnablerClientRpc();
}
}
[ClientRpc]
void timerTextEnablerClientRpc()
{
timerText.gameObject.SetActive ( true );
}
public float GetRemainingTime()
{
return timer.Value;
}
private void OnEnable()
{
timer.OnValueChanged += OnTimerValueChanged;
}
private void OnDisable()
{
timer.OnValueChanged -= OnTimerValueChanged;
}
private void OnTimerValueChanged(float oldValue, float newValue)
{
if (newValue <= 0 && oldValue > 0)
{
OnTimerEnd?.Invoke();
}
UpdateTimerUI();
}
private void UpdateTimerUI()
{
if (timerText != null)
{
int minutes = Mathf.FloorToInt(timer.Value / 60);
int seconds = Mathf.FloorToInt(timer.Value % 60);
timerText.text = $"{minutes:D2}:{seconds:D2}";
}
}
}