52 lines
2.0 KiB
C#
52 lines
2.0 KiB
C#
using System.Collections.Generic;
|
|
using System.Text;
|
|
using UnityEngine;
|
|
|
|
// 대화 텍스트의 {key} 토큰을 런타임 값으로 치환하는 전역 저장소.
|
|
// 예) DialogVariables.Set("playerName", "철수");
|
|
// 대사 "안녕 {playerName}!" → "안녕 철수!"
|
|
//
|
|
// 표시 직전(DialogHud / ChoiceHud)에서 Format()을 거치므로, 그래프엔 그냥 {key}만 써두면 된다.
|
|
public static class DialogVariables
|
|
{
|
|
private static readonly Dictionary<string, string> _values = new();
|
|
|
|
public static void Set(string key, string value) => _values[key] = value ?? string.Empty;
|
|
public static void Remove(string key) => _values.Remove(key);
|
|
public static void Clear() => _values.Clear();
|
|
public static bool TryGet(string key, out string value) => _values.TryGetValue(key, out value);
|
|
|
|
// "{key}" 토큰을 등록된 값으로 치환. 등록 안 된 키는 그대로 둔다(빠진 값 디버깅용).
|
|
public static string Format(string text)
|
|
{
|
|
if (string.IsNullOrEmpty(text) || text.IndexOf('{') < 0) return text;
|
|
|
|
var sb = new StringBuilder(text.Length);
|
|
int i = 0;
|
|
while (i < text.Length)
|
|
{
|
|
if (text[i] == '{')
|
|
{
|
|
int close = text.IndexOf('}', i + 1);
|
|
if (close > i)
|
|
{
|
|
string key = text.Substring(i + 1, close - i - 1);
|
|
if (_values.TryGetValue(key, out var val))
|
|
{
|
|
sb.Append(val);
|
|
i = close + 1;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
sb.Append(text[i]);
|
|
i++;
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
// 플레이 시작마다 초기화 (Enter Play Mode에서 도메인 리로드를 꺼도 이전 값이 안 남게)
|
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
|
private static void ResetOnPlay() => _values.Clear();
|
|
}
|