87 lines
2.3 KiB
C#
87 lines
2.3 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
using System.Linq;
|
|
namespace BITKit.UX
|
|
{
|
|
public class UXTranslator : MonoBehaviour
|
|
{
|
|
[System.Serializable]
|
|
public struct Element<T> where T : VisualElement
|
|
{
|
|
public string source;
|
|
public T element;
|
|
}
|
|
public UIDocument document;
|
|
public List<Element<Label>> labels = new();
|
|
public List<Element<Button>> buttons = new();
|
|
ITranslator translator;
|
|
void Start()
|
|
{
|
|
var root = document.rootVisualElement;
|
|
|
|
labels = root.Query<Label>()
|
|
.ToList()
|
|
.Where(x => x.text.Contains("#"))
|
|
.Select(x => new Element<Label>()
|
|
{
|
|
source = x.text,
|
|
element = x
|
|
}).ToList();
|
|
|
|
buttons = root.Query<Button>()
|
|
.ToList()
|
|
.Where(x => x.text.Contains("#"))
|
|
.Select(x => new Element<Button>()
|
|
{
|
|
source = x.text,
|
|
element = x,
|
|
}).ToList();
|
|
|
|
|
|
Translate();
|
|
|
|
|
|
|
|
translator = DI.Get<ITranslator>();
|
|
|
|
translator.OnChangeLanguage += Translate;
|
|
translator.OnCollageAllSourceText += GetAllSourceText;
|
|
}
|
|
public void Translate(string langs)
|
|
{
|
|
Translate();
|
|
}
|
|
[ContextMenu(nameof(Translate))]
|
|
public void Translate()
|
|
{
|
|
var translator = DI.Get<ITranslator>();
|
|
string newText;
|
|
foreach (var element in labels)
|
|
{
|
|
newText = translator.Translate(element.source);
|
|
element.element.text = newText;
|
|
}
|
|
foreach (var element in buttons)
|
|
{
|
|
newText = translator.Translate(element.source);
|
|
element.element.text = newText;
|
|
}
|
|
}
|
|
void OnDestroy()
|
|
{
|
|
translator.OnChangeLanguage -= Translate;
|
|
translator.OnCollageAllSourceText -= GetAllSourceText;
|
|
}
|
|
string[] GetAllSourceText()
|
|
{
|
|
List<string> list = new();
|
|
|
|
list.AddRange(labels.Select(x => x.source));
|
|
list.AddRange(buttons.Select(x => x.source));
|
|
return list.ToArray();
|
|
}
|
|
}
|
|
}
|