Skip to content

Instantly share code, notes, and snippets.

@noio
Created March 9, 2023 12:32
Show Gist options
  • Save noio/9319c2c3c8cbff7dd8bb66ed39efbe52 to your computer and use it in GitHub Desktop.
Save noio/9319c2c3c8cbff7dd8bb66ed39efbe52 to your computer and use it in GitHub Desktop.
Implementation of a Player Option for Language setting
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Localization;
using UnityEngine.Localization.Pseudo;
using UnityEngine.Localization.Settings;
#if UNITY_EDITOR
#endif
namespace PlantsGame.PlayerOptions
{
[CreateAssetMenu(menuName = "Noio/Player Options/Language", fileName = "Language", order = 0)]
public class OptionLanguage : OptionValue<string>
{
#region PROPERTIES
public List<Locale> Locales { get; private set; }
#endregion
public override void LoadValue()
{
base.LoadValue();
Assert.IsTrue(string.IsNullOrEmpty(DefaultValue),
"Default language should be empty, is managed through LocaleSelector");
/*
* Language option is unique because
* it handles its own change.
*/
ValueChanged += SetLocaleFromIdentifier;
LocalizationSettings.InitializationOperation.Completed += _ =>
{
Locales = LocalizationSettings.AvailableLocales.Locales.Where(l => l is PseudoLocale == false).ToList();
/*
* Base.Init will do load, if no value was loaded, (null or empty)
* set Value to the LocalizationSystem's SelectedLocale
*/
if (string.IsNullOrEmpty(Value))
{
LocalizationSettings.SelectedLocaleAsync.Completed += h2 =>
{
Value = h2.Result.Identifier.Code;
};
}
else
{
SetLocaleFromIdentifier(Value);
}
};
}
void SetLocaleFromIdentifier(string identifier)
{
var foundLocale = LocalizationSettings.AvailableLocales.GetLocale(identifier);
if (foundLocale != null)
{
LocalizationSettings.SelectedLocale = foundLocale;
}
}
protected override string Load()
{
return Prefs.GetString(PrefsKey);
}
protected override void Store(string value)
{
Prefs.SetString(PrefsKey, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment