Files
Gen_Hack-and-Slash-Roguelite/Client/Assets/Scripts/UI/BarUI.cs

69 lines
2.8 KiB
C#
Raw 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 UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class BarUI : MonoBehaviour
{
[SerializeField] private Image image;
[Header("Progress Gradient")] [SerializeField]
private Gradient progressGradient; // 用于定义多色进度渐变
[Header("Editor Preview")] [SerializeField] [Range(0, 1)]
private float _editorProgressPreview = 0f; // 用于在编辑器中预览的进度值
/// <summary>
/// 获取或设置进度条的当前进度 (0-1)。
/// 设置时会同时更新进度条的填充量和根据渐变更新颜色。
/// </summary>
public float Progress
{
get => image.fillAmount;
set
{
// 在运行时检查image是否已赋值
if (image == null)
{
Debug.LogWarning("BarUI: Image reference is not set! Cannot update progress or color.", this);
return;
}
// 确保进度值在0到1之间防止出现异常情况
float clampedValue = Mathf.Clamp01(value);
image.fillAmount = clampedValue;
// 使用Gradient的Evaluate方法根据进度值获取对应的渐变颜色
// Unity编辑器会自动为Gradient字段初始化一个默认实例但在某些特殊运行时情况下
// 还是可以加一个null检查以增加健壮性。
if (progressGradient != null)
{
image.color = progressGradient.Evaluate(clampedValue);
}
else
{
// 如果梯度未定义(极少发生),则使用默认颜色并发出警告
Debug.LogWarning("BarUI: Progress Gradient is not set! Using default white color.", this);
image.color = Color.white;
}
}
}
// OnValidate是Unity编辑器特有的方法当脚本实例在编辑器中被加载或Inspector中的数据被修改时调用
private void OnValidate()
{
// 只有当存在Image引用时才进行更新避免在编辑器中因未赋值而引发NullReferenceException
if (image != null)
{
// 在编辑器中修改_editorProgressPreview时同步更新实际的Progress
// 这会触发Progress属性的setter进而更新fillAmount和color
Progress = _editorProgressPreview;
}
else
{
// 在编辑器中未分配Image时给出提示防止用户迷惑
Debug.LogWarning("BarUI: Image reference is not assigned. Editor preview disabled.", this);
}
}
}
}