Files
BABA_YAGA/Assets/Scripts/UI/LocalizationManager.cs

87 lines
2.8 KiB
C#
Raw Normal View History

2026-04-29 02:31:15 +07:00
using System;
using System.Collections.Generic;
2026-05-01 17:57:07 +07:00
using System.Text.RegularExpressions;
2026-04-29 02:31:15 +07:00
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);
2026-05-01 17:57:07 +07:00
// Đọc ngôn ngữ đã lưu hoặc mặc định là tiếng Anh
string savedLang = PlayerPrefs.GetString("Language", "en");
LoadLanguage(savedLang);
2026-04-29 02:31:15 +07:00
}
else
{
Destroy(gameObject);
}
}
public void LoadLanguage(string langCode)
{
_currentLanguage = langCode;
TextAsset jsonAsset = Resources.Load<TextAsset>($"Localization/{langCode}");
if (jsonAsset != null)
{
2026-05-01 17:57:07 +07:00
ParseJsonRobust(jsonAsset.text);
2026-04-29 02:31:15 +07:00
PlayerPrefs.SetString("Language", langCode);
PlayerPrefs.Save();
2026-05-01 17:57:07 +07:00
// Thông báo cho các UI khác biết ngôn ngữ đã đổi
2026-04-29 02:31:15 +07:00
OnLanguageChanged?.Invoke();
2026-05-01 17:57:07 +07:00
Debug.Log($"[Localization] Successfully loaded language: {langCode} ({_localizedText.Count} keys)");
2026-04-29 02:31:15 +07:00
}
else
{
2026-05-01 17:57:07 +07:00
Debug.LogError($"[Localization] Language file NOT FOUND in Resources/Localization/{langCode}");
2026-04-29 02:31:15 +07:00
}
}
2026-05-01 17:57:07 +07:00
// Dùng Regex để bóc tách Key-Value từ JSON cực kỳ chính xác
private void ParseJsonRobust(string json)
2026-04-29 02:31:15 +07:00
{
_localizedText.Clear();
2026-05-01 17:57:07 +07:00
// 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)
2026-04-29 02:31:15 +07:00
{
2026-05-01 17:57:07 +07:00
if (match.Groups.Count == 3)
2026-04-29 02:31:15 +07:00
{
2026-05-01 17:57:07 +07:00
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
_localizedText[key] = value;
2026-04-29 02:31:15 +07:00
}
}
}
public string GetLocalizedString(string key)
{
2026-05-01 17:57:07 +07:00
if (_localizedText.TryGetValue(key, out string value))
2026-04-29 02:31:15 +07:00
{
return value;
}
2026-05-01 17:57:07 +07:00
return key; // Trả về chính key nếu không tìm thấy dịch thuật
2026-04-29 02:31:15 +07:00
}
public string CurrentLanguage => _currentLanguage;
}
}