87 lines
2.8 KiB
C#
87 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.RegularExpressions;
|
|
using UnityEngine;
|
|
|
|
namespace Hallucinate.UI
|
|
{
|
|
public class LocalizationManager : MonoBehaviour
|
|
{
|
|
public static LocalizationManager Instance { get; private set; }
|
|
|
|
private Dictionary<string, string> _localizedText = new Dictionary<string, string>();
|
|
private string _currentLanguage = "en";
|
|
|
|
public event Action OnLanguageChanged;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance == null)
|
|
{
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
|
|
// Đọc ngôn ngữ đã lưu hoặc mặc định là tiếng Anh
|
|
string savedLang = PlayerPrefs.GetString("Language", "en");
|
|
LoadLanguage(savedLang);
|
|
}
|
|
else
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
public void LoadLanguage(string langCode)
|
|
{
|
|
_currentLanguage = langCode;
|
|
TextAsset jsonAsset = Resources.Load<TextAsset>($"Localization/{langCode}");
|
|
|
|
if (jsonAsset != null)
|
|
{
|
|
ParseJsonRobust(jsonAsset.text);
|
|
|
|
PlayerPrefs.SetString("Language", langCode);
|
|
PlayerPrefs.Save();
|
|
|
|
// Thông báo cho các UI khác biết ngôn ngữ đã đổi
|
|
OnLanguageChanged?.Invoke();
|
|
Debug.Log($"[Localization] Successfully loaded language: {langCode} ({_localizedText.Count} keys)");
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError($"[Localization] Language file NOT FOUND in Resources/Localization/{langCode}");
|
|
}
|
|
}
|
|
|
|
// Dùng Regex để bóc tách Key-Value từ JSON cực kỳ chính xác
|
|
private void ParseJsonRobust(string json)
|
|
{
|
|
_localizedText.Clear();
|
|
|
|
// Regex này sẽ tìm tất cả các cặp "key" : "value" bất kể khoảng trắng hay xuống dòng
|
|
MatchCollection matches = Regex.Matches(json, "\"([^\"]+)\"\\s*:\\s*\"([^\"]+)\"");
|
|
|
|
foreach (Match match in matches)
|
|
{
|
|
if (match.Groups.Count == 3)
|
|
{
|
|
string key = match.Groups[1].Value;
|
|
string value = match.Groups[2].Value;
|
|
_localizedText[key] = value;
|
|
}
|
|
}
|
|
}
|
|
|
|
public string GetLocalizedString(string key)
|
|
{
|
|
if (_localizedText.TryGetValue(key, out string value))
|
|
{
|
|
return value;
|
|
}
|
|
return key; // Trả về chính key nếu không tìm thấy dịch thuật
|
|
}
|
|
|
|
public string CurrentLanguage => _currentLanguage;
|
|
}
|
|
}
|