DCS/ruiyiweiUX/Assets/Scripts/Components/TimeUpdateComponent.cs

114 lines
2.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using TMPro;
using UnityEngine;
/// <summary>
/// 时间更新组件
/// 独立于BasePanel的Update系统专门用于更新UI中的时间显示
/// </summary>
public class TimeUpdateComponent : MonoBehaviour
{
[Header("时间显示组件")]
public TextMeshProUGUI DateTimeText;
[Header("更新设置")]
public float UpdateInterval = 1f; // 更新间隔(秒)
public string TimeFormat = "yyyy-MM-dd HH:mm:ss"; // 时间格式
public bool UseLocalTime = true; // 使用本地时间还是UTC时间
private float _lastUpdateTime;
private bool _isActive = true;
void Start()
{
// 立即更新一次
UpdateDateTime();
}
void Update()
{
if (!_isActive || DateTimeText == null) return;
// 检查是否需要更新
if (Time.time - _lastUpdateTime >= UpdateInterval)
{
UpdateDateTime();
_lastUpdateTime = Time.time;
}
}
/// <summary>
/// 更新时间显示
/// </summary>
private void UpdateDateTime()
{
if (DateTimeText != null)
{
// 从SystemSettingsService获取统一时间默认跟随系统时钟可选自定义偏移
var settingsService = ServiceLocator.Get<ISystemSettingsService>();
DateTime displayTime = settingsService != null
? settingsService.SystemTime
: (UseLocalTime ? DateTime.Now : DateTime.UtcNow);
DateTimeText.text = displayTime.ToString(TimeFormat);
}
}
/// <summary>
/// 启用或禁用时间更新
/// </summary>
public void SetActive(bool active)
{
_isActive = active;
if (active)
{
UpdateDateTime(); // 激活时立即更新
}
}
/// <summary>
/// 设置时间格式
/// </summary>
public void SetTimeFormat(string format)
{
if (!string.IsNullOrEmpty(format))
{
TimeFormat = format;
UpdateDateTime(); // 格式改变后立即更新
}
}
/// <summary>
/// 设置更新间隔
/// </summary>
public void SetUpdateInterval(float interval)
{
if (interval > 0)
{
UpdateInterval = interval;
}
}
/// <summary>
/// 刷新配置时间从SystemSettingsService重新读取
/// </summary>
public void RefreshConfigTime()
{
UpdateDateTime();
Debug.Log("TimeUpdateComponent: 已刷新配置时间");
}
/// <summary>
/// 获取当前显示的时间(包括偏移计算)
/// </summary>
public DateTime GetCurrentDisplayTime()
{
var settingsService = ServiceLocator.Get<ISystemSettingsService>();
if (settingsService != null)
{
return settingsService.SystemTime;
}
return UseLocalTime ? DateTime.Now : DateTime.UtcNow;
}
}