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

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
User avatar
Tony Li
Posts: 22156
Joined: Thu Jul 18, 2013 1:27 pm

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

Post 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
Post Reply