Update
This commit is contained in:
96
Assets/Scripts/UI/LocalizationManager.cs
Normal file
96
Assets/Scripts/UI/LocalizationManager.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
|
||||
[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"));
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
public void LoadLanguage(string langCode)
|
||||
{
|
||||
_currentLanguage = langCode;
|
||||
TextAsset jsonAsset = Resources.Load<TextAsset>($"Localization/{langCode}");
|
||||
|
||||
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);
|
||||
|
||||
PlayerPrefs.SetString("Language", langCode);
|
||||
PlayerPrefs.Save();
|
||||
OnLanguageChanged?.Invoke();
|
||||
Debug.Log($"[Localization] Loaded language: {langCode}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"[Localization] Language file not found: Localization/{langCode}");
|
||||
}
|
||||
}
|
||||
|
||||
private void ParseFlatJson(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)
|
||||
{
|
||||
string[] kv = pair.Split(new[] { "\":\"" }, StringSplitOptions.None);
|
||||
if (kv.Length == 2)
|
||||
{
|
||||
string key = kv[0].Trim().Trim('"', ' ', '\t', '\r');
|
||||
string val = kv[1].Trim().Trim('"', ' ', '\t', '\r');
|
||||
_localizedText[key] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string GetLocalizedString(string key)
|
||||
{
|
||||
if (_localizedText != null && _localizedText.TryGetValue(key, out string value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
public string CurrentLanguage => _currentLanguage;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user