76 lines
1.9 KiB
C#
76 lines
1.9 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(TextMeshProUGUI))]
|
|
public class digits_sheet_auto : MonoBehaviour
|
|
{
|
|
[SerializeField, Tooltip("要显示的数字,支持小数和负数")]
|
|
private double value;
|
|
|
|
[SerializeField, Tooltip("是否显示千分位逗号")]
|
|
private bool showComma = true;
|
|
|
|
[SerializeField, Tooltip("最多保留几位小数,尾数为 0 时不显示")]
|
|
private int decimalPlaces = 3;
|
|
|
|
private TextMeshProUGUI label;
|
|
|
|
private void Awake()
|
|
{
|
|
label = GetComponent<TextMeshProUGUI>();
|
|
if (label == null)
|
|
label = gameObject.AddComponent<TextMeshProUGUI>();
|
|
|
|
label.richText = true;
|
|
Refresh();
|
|
}
|
|
|
|
private void OnValidate()
|
|
{
|
|
label = GetComponent<TextMeshProUGUI>();
|
|
if (label != null)
|
|
Refresh();
|
|
}
|
|
|
|
public void SetValue(double newValue)
|
|
{
|
|
value = newValue;
|
|
Refresh();
|
|
}
|
|
|
|
private void Refresh()
|
|
{
|
|
if (label == null)
|
|
return;
|
|
|
|
int places = Mathf.Clamp(decimalPlaces, 0, 15);
|
|
string format = showComma ? "#,##0" : "0";
|
|
if (places > 0)
|
|
format += "." + new string('#', places);
|
|
|
|
string number = value.ToString(format, CultureInfo.InvariantCulture);
|
|
label.text = ToSpriteTags(number);
|
|
}
|
|
|
|
private static string ToSpriteTags(string number)
|
|
{
|
|
var sb = new StringBuilder(number.Length * 24);
|
|
|
|
foreach (char c in number)
|
|
{
|
|
if (c >= '0' && c <= '9')
|
|
sb.Append("<sprite name=\"").Append(c).Append("\">");
|
|
else if (c == ',')
|
|
sb.Append("<sprite name=\"comma\">");
|
|
else if (c == '.')
|
|
sb.Append("<sprite name=\"dot\">");
|
|
else
|
|
sb.Append(c); // 图集里没有负号,负号退回普通字体
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
}
|