Page 1 of 1

[HOWTO] How To: Set Up Language Selection UI Buttons

Posted: Thu Nov 25, 2021 1:17 pm
by Tony Li
To change languages, call DialogueManager.SetLanguage() in script. Here's an example script that you can add to a UI Button:
LanguageButton.cs

Code: Select all

using UnityEngine;
using UnityEngine.UI;
using PixelCrushers.DialogueSystem;

[RequireComponent(typeof(Button))]
public class LanguageButton : MonoBehaviour
{
    public bool isDefaultLanguage;
    public bool useLanguageName;
    public string languageName;
    public string languageCode;

    public Button button { get; private set; }

    private string GetThisLanguage()
    {
        return useLanguageName ? languageName : languageCode;
    }

    private void Start()
    {
        // Store a reference to the UI button:
        button = GetComponent<Button>();

        // Update the label:
        var text = GetComponentInChildren<Text>();
        if (text != null) text.text = languageName;

        // Set the button interactable or not:
        var isCurrentLanguage = Localization.language == GetThisLanguage() || (Localization.isDefaultLanguage && isDefaultLanguage);
        button.interactable = !isCurrentLanguage;

        // Set the button's OnClick() event:
        button.onClick.AddListener(SetThisLanguage);
    }

    private void SetThisLanguage()
    {
        // Use this button's language:
        DialogueManager.SetLanguage(GetThisLanguage());

        // Update buttons interactable or not:
        button.interactable = false;
        foreach (LanguageButton languageButton in FindObjectsOfType<LanguageButton>())
        {
            languageButton.button.interactable = languageButton != this;
        }
    }
}
Here's an example scene exported from Unity 2020 that uses the script:

DS_SetLanguageButtonExample_2021-11-25.unitypackage


Related: How To: Update Currently-Displayed Text When Changing Language