Last active
April 8, 2026 19:15
-
-
Save andrew-raphael-lukasik/e4ae9b45a2c24672c0d1218f77235948 to your computer and use it in GitHub Desktop.
Language selection menu (for UIToolkit @ Unity)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // void* src = https://gist.github.com/andrew-raphael-lukasik/e4ae9b45a2c24672c0d1218f77235948 | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using UnityEngine; | |
| using UnityEngine.UIElements; | |
| using UnityEngine.Localization; | |
| using UnityEngine.Localization.Settings; | |
| using UnityEngine.ResourceManagement.AsyncOperations; | |
| namespace Localization | |
| { | |
| [UnityEngine.Scripting.Preserve] | |
| [UxmlElement] | |
| public partial class LocaleList : VisualElement | |
| { | |
| #region fields | |
| ListView _listView = null; | |
| #endregion | |
| #region constructors | |
| public LocaleList() | |
| { | |
| var selectedLocale = LocalizationSettings.SelectedLocale;// forces synchronous load | |
| _listView = new ListView( | |
| itemsSource: LocalizationSettings.AvailableLocales.Locales , | |
| itemHeight: 16 , | |
| makeItem: OnMakeItem , | |
| bindItem: OnBindItem | |
| ); | |
| _listView.selectionType = SelectionType.Single; | |
| { | |
| var style = _listView.style; | |
| style.minHeight = 16; | |
| } | |
| this.Add(_listView); | |
| _listView.itemsChosen += OnItemsChosen; | |
| _listView.Rebuild(); | |
| LocalizationSettings.SelectedLocaleChanged += LocalizationSettings_SelectedLocaleChanged; | |
| } | |
| #endregion | |
| #region private methods | |
| VisualElement OnMakeItem() | |
| { | |
| return new Label(); | |
| } | |
| void OnBindItem( | |
| VisualElement ve, | |
| int index | |
| ) | |
| { | |
| Label label = (Label) ve; | |
| Locale locale = LocalizationSettings.AvailableLocales.Locales[index]; | |
| label.text = locale.Identifier.CultureInfo.NativeName; | |
| } | |
| void OnItemsChosen(IEnumerable<object> objects) | |
| { | |
| if (objects.FirstOrDefault() is Locale locale) | |
| ChangeLocale(locale); | |
| } | |
| void ChangeLocale(Locale locale) | |
| { | |
| if (locale!=null) | |
| { | |
| LocalizationSettings.SelectedLocaleChanged -= LocalizationSettings_SelectedLocaleChanged; | |
| LocalizationSettings.SelectedLocale = locale; | |
| LocalizationSettings.SelectedLocaleChanged += LocalizationSettings_SelectedLocaleChanged; | |
| } | |
| else Debug.LogWarning("locale object is null"); | |
| } | |
| void LocalizationSettings_SelectedLocaleChanged(Locale locale) | |
| { | |
| int idx = LocalizationSettings.AvailableLocales.Locales.IndexOf(locale); | |
| _listView.ScrollToItem(idx); | |
| } | |
| #endregion | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment