94 lines
3.5 KiB
C#
94 lines
3.5 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using AibisDream.Framework;
|
|
using AibisDream.Utility;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace AibisDream.UI
|
|
{
|
|
public class VariableBar : MonoBehaviour
|
|
{
|
|
[SerializeField] private ScrollRect scrollRect;
|
|
[SerializeField] private TMP_Text variableText;
|
|
|
|
private Dictionary<string, TMP_Text> _variableTextDict = new();
|
|
|
|
private void OnEnable()
|
|
{
|
|
|
|
// 读取存储中所有变量并打印
|
|
var variables = StorageSystem.Instance.GetAllVariables();
|
|
PrintAllVariables(variables);
|
|
EnumEventSystem.Global.Register<StorageEvent, VariableItem>(StorageEvent.VariableSet, OnVariableUpdate);
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
ClearAllVariables();
|
|
EnumEventSystem.Global.UnRegister<StorageEvent, VariableItem>(StorageEvent.VariableSet, OnVariableUpdate);
|
|
}
|
|
|
|
private void PrintAllVariables((Dictionary<string, float> FloatVariables, Dictionary<string, string> StringVariables,
|
|
Dictionary<string, bool> BoolVariables) variables)
|
|
{
|
|
// 先把所有变量整理为文字
|
|
Dictionary<string, string> variableStrDict = new Dictionary<string, string>();
|
|
foreach (var variable in variables.FloatVariables)
|
|
{
|
|
variableStrDict.Add(variable.Key, $"{variable.Key}: {variable.Value}");
|
|
}
|
|
foreach (var variable in variables.StringVariables)
|
|
{
|
|
variableStrDict.Add(variable.Key, $"{variable.Key}: {variable.Value}");
|
|
}
|
|
foreach (var variable in variables.BoolVariables)
|
|
{
|
|
variableStrDict.Add(variable.Key, $"{variable.Key}: {variable.Value}");
|
|
}
|
|
|
|
// 整理文字后按Key的字典序排序
|
|
var sortedVariableStrArr = variableStrDict.OrderBy(item => item.Key).Select(item => item.Value).ToList();
|
|
// 将每个条目放到TMP里
|
|
foreach (var variableStr in sortedVariableStrArr)
|
|
{
|
|
var item = Instantiate(variableText, scrollRect.content);
|
|
item.text = variableStr;
|
|
|
|
_variableTextDict.Add(variableStr, item);
|
|
}
|
|
}
|
|
|
|
private void OnVariableUpdate(VariableItem variableItem)
|
|
{
|
|
if (_variableTextDict.TryGetValue(variableItem.variableName, out var text))
|
|
{
|
|
text.text = $"{variableItem.variableName}: {variableItem.value}";
|
|
}
|
|
else
|
|
{
|
|
var item = Instantiate(variableText, scrollRect.content);
|
|
item.text = $"{variableItem.variableName}: {variableItem.value}";
|
|
_variableTextDict.Add(variableItem.variableName, item);
|
|
// 按字典序插入子类
|
|
// 先找到插入位置
|
|
var sortedVariableStrArr = _variableTextDict.Keys.OrderBy(item => item).ToList();
|
|
var insertIdx = sortedVariableStrArr.FindIndex(item => item.CompareTo(variableItem.variableName) > 0);
|
|
if (insertIdx < 0)
|
|
{
|
|
insertIdx = sortedVariableStrArr.Count;
|
|
}
|
|
// 插入
|
|
item.transform.SetSiblingIndex(insertIdx);
|
|
}
|
|
}
|
|
|
|
private void ClearAllVariables()
|
|
{
|
|
scrollRect.content.DestroyAllChildren();
|
|
|
|
_variableTextDict.Clear();
|
|
}
|
|
}
|
|
} |