Search Unity

Showcase Translation/Localization for UI Toolkit ( c# script code )

Discussion in 'UI Toolkit' started by drbatuira, Jun 12, 2022.

  1. drbatuira

    drbatuira

    Joined:
    May 4, 2020
    Posts:
    23
    Hello.

    For those who want to integrate Unity Localization with the UI Toolkit, here is one of the possible solutions.

    In the last few days I had some problems translating/localizing my game. Then I found a post (https://forum.unity.com/threads/ui-toolkit-support.974994/#post-6344760)[ @andrew-lukasik ], with a code to translate the interface (thanks a lot)

    His code bugged my buttons, they no longer received click events.

    So I made mine based on his, credits to him :)

    To use, add the script to the component that has the UIDocument, select the table and run (be happy).

    As explained by user andrew-lukasik, the keys must start with "#".




    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3. using UnityEngine.Localization;
    4. using UnityEngine.Localization.Tables;
    5. using UnityEngine.ResourceManagement.AsyncOperations;
    6. using UnityEngine.UIElements;
    7.  
    8. [DisallowMultipleComponent]
    9. [RequireComponent(typeof(UIDocument))]
    10. public class UIToolkitLocalization : MonoBehaviour
    11. {
    12.     [SerializeField] LocalizedStringTable table;
    13.     List<LocalizeObj> elementList = new List<LocalizeObj>();
    14.  
    15.     void Awake()
    16.     {
    17.         var document = gameObject.GetComponentInParent<UIDocument>(includeInactive: true);
    18.         RegisterElements(document.rootVisualElement);//Register all text elements
    19.     }
    20.  
    21.     void OnEnable() => table.TableChanged += OnTableChanged;
    22.  
    23.     void OnDisable() => table.TableChanged -= OnTableChanged;
    24.  
    25.     void OnTableChanged(StringTable stringTable)//if you change the language, the values are updated
    26.     {
    27.         var tb = table.GetTableAsync();
    28.         tb.Completed -= OnTableLoaded;
    29.         tb.Completed += OnTableLoaded;
    30.     }
    31.  
    32.     void OnTableLoaded(AsyncOperationHandle<StringTable> table)//Updates values if language changes
    33.     {
    34.         Localize(table.Result);
    35.     }
    36.  
    37.     void RegisterElements(VisualElement element)//Register all elements ( recursive )
    38.     {
    39.         //if have text
    40.         if (typeof(TextElement).IsInstanceOfType(element))
    41.         {
    42.             var textElement = (TextElement)element;
    43.             var key = textElement.text;
    44.             if (!string.IsNullOrEmpty(key) && key[0] == '#')
    45.             {
    46.                 key = key.TrimStart('#');
    47.                 elementList.Add(new LocalizeObj
    48.                 {
    49.                     Element = textElement,
    50.                     Key = key
    51.                 });
    52.             }
    53.         }
    54.         //if have child
    55.         var hierarchy = element.hierarchy;
    56.         var childs = hierarchy.childCount;
    57.         for (int i = 0; i < childs; i++)
    58.         {
    59.             RegisterElements(hierarchy.ElementAt(i));
    60.         }
    61.     }
    62.  
    63.     void Localize(StringTable stringTable)//Change text values
    64.     {
    65.         foreach (var item in elementList)
    66.         {
    67.             var entry = stringTable[item.Key];
    68.             if (entry != null)
    69.                 item.Element.text = entry.LocalizedValue;
    70.             else
    71.                 Debug.LogWarning($"No {stringTable.LocaleIdentifier.Code} translation for key: '{item.Key}'");
    72.         }
    73.     }
    74.  
    75.     class LocalizeObj//Used for translation
    76.     {
    77.         public string Key;
    78.         public TextElement Element;
    79.     }
    80. }
     
    Last edited: Jun 12, 2022
    abegue, AlejandroMJ, Rogilla and 3 others like this.