Update Setting

This commit is contained in:
2026-05-01 17:57:07 +07:00
parent bcb2c329c5
commit 9c784e77f8
26 changed files with 954 additions and 3233 deletions

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace Hallucinate.UI
@@ -13,26 +14,16 @@ namespace Hallucinate.UI
public event Action OnLanguageChanged;
[Serializable]
private class LocalizationData
{
public List<LocalizationEntry> items;
}
[Serializable]
private class LocalizationEntry
{
public string key;
public string value;
}
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
LoadLanguage(PlayerPrefs.GetString("Language", "en"));
// Đọc ngôn ngữ đã lưu hoặc mặc định là tiếng Anh
string savedLang = PlayerPrefs.GetString("Language", "en");
LoadLanguage(savedLang);
}
else
{
@@ -47,48 +38,47 @@ namespace Hallucinate.UI
if (jsonAsset != null)
{
// Vì JsonUtility không hỗ trợ Dictionary, chúng ta parse tay một chút nếu file là JSON object phẳng
// Hoặc giả định file JSON có cấu trúc phù hợp.
// Ở đây tôi sẽ dùng giải pháp parse đơn giản cho JSON phẳng { "key": "value" }
ParseFlatJson(jsonAsset.text);
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] Loaded language: {langCode}");
Debug.Log($"[Localization] Successfully loaded language: {langCode} ({_localizedText.Count} keys)");
}
else
{
Debug.LogError($"[Localization] Language file not found: Localization/{langCode}");
Debug.LogError($"[Localization] Language file NOT FOUND in Resources/Localization/{langCode}");
}
}
private void ParseFlatJson(string json)
// 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();
// Xóa các ký tự thừa
json = json.Trim().Trim('{', '}');
string[] pairs = json.Split(new[] { "\",", "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var pair in pairs)
// 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)
{
string[] kv = pair.Split(new[] { "\":\"" }, StringSplitOptions.None);
if (kv.Length == 2)
if (match.Groups.Count == 3)
{
string key = kv[0].Trim().Trim('"', ' ', '\t', '\r');
string val = kv[1].Trim().Trim('"', ' ', '\t', '\r');
_localizedText[key] = val;
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
_localizedText[key] = value;
}
}
}
public string GetLocalizedString(string key)
{
if (_localizedText != null && _localizedText.TryGetValue(key, out string value))
if (_localizedText.TryGetValue(key, out string value))
{
return value;
}
return key;
return key; // Trả về chính key nếu không tìm thấy dịch thuật
}
public string CurrentLanguage => _currentLanguage;