52 lines
2.0 KiB
C#
52 lines
2.0 KiB
C#
using UnityEngine;
|
||
|
||
namespace BaseGames.Localization
|
||
{
|
||
/// <summary>
|
||
/// 语言设置持久化 SO(架构 16_SupportingModules §4.1)。
|
||
/// 支持的语言列表由设计师填写;当前语言持久化到 PlayerPrefs。
|
||
/// </summary>
|
||
[CreateAssetMenu(menuName = "BaseGames/Settings/LanguageManager", fileName = "SET_LanguageManager")]
|
||
public class LanguageManagerSO : ScriptableObject
|
||
{
|
||
private const string PrefsKey = "game_language";
|
||
|
||
[Tooltip("游戏支持的语言 locale code 列表(如 zh-CN、en-US)")]
|
||
public string[] supportedLocales = { "zh-CN", "en-US" };
|
||
|
||
[Tooltip("默认语言 locale code")]
|
||
public string defaultLocale = "zh-CN";
|
||
|
||
public string CurrentLocale { get; private set; }
|
||
|
||
private void OnEnable()
|
||
{
|
||
CurrentLocale = PlayerPrefs.GetString(PrefsKey, defaultLocale);
|
||
}
|
||
|
||
/// <summary>设置当前语言并持久化到 PlayerPrefs,同时通知 Unity Localization(若已安装)。</summary>
|
||
public void SetLocale(string localeCode)
|
||
{
|
||
CurrentLocale = localeCode;
|
||
PlayerPrefs.SetString(PrefsKey, localeCode);
|
||
PlayerPrefs.Save();
|
||
ApplyLocale(localeCode);
|
||
}
|
||
|
||
/// <summary>初始化时应用已保存语言。</summary>
|
||
public void ApplySaved() => ApplyLocale(CurrentLocale);
|
||
|
||
private static void ApplyLocale(string localeCode)
|
||
{
|
||
#if UNITY_LOCALIZATION
|
||
var locales = UnityEngine.Localization.Settings.LocalizationSettings.AvailableLocales;
|
||
var locale = locales?.GetLocale(new UnityEngine.Localization.LocaleIdentifier(localeCode));
|
||
if (locale != null)
|
||
UnityEngine.Localization.Settings.LocalizationSettings.SelectedLocale = locale;
|
||
#else
|
||
Debug.Log($"[LanguageManager] 语言设为 {localeCode}(Unity Localization 包未安装,仅记录 PlayerPrefs)。");
|
||
#endif
|
||
}
|
||
}
|
||
}
|