Localizzare con lo scripting

Puoi utilizzare le API di localizzazione per attività di traduzione specializzate che non vengono gestite automaticamente dall'aggiunta di traduzioni alla tabella di Localizzazione. Roblox mette a disposizione unLocalizationService per gestire tutti i bisogni di scripting di Localizzazione. Utilizza laLocalizationService per le seguenti attività:

Se utilizzi le API di Localizzazione durante la traduzione dell'esperienza, ascolta le modifiche al LocaleID dell'utente per rispondere agli utenti che cambiano la propria lingua durante un'esperienza.

Quando si riutilizza un codice di traduzione, dovresti usare unTranslationHelper ModuleScriptper gestire gli errori e le traduzioni mancanti.

Localizzazione di Immagini e Suoni

Aggiungi la Localizzazione oltre al testo nella tua esperienza, fornendo immagini e suoni unici a seconda della località dell'utente. Per localizzare risorse, aggiungi prima gli ID della Sorgente e gli ID delle risorse di destinazione alla tabella di localizzazione dell'esperienza poi usa l'API di Localizzazione per recuperare le diverse sorgenti.

Inglese (Sorgente) - rbxassetid://2957093606
Spagnolo (sp) - rbxassetid://2957093671
Portoghese (pt) - rbxassetid://2957093727

Per iniziare a localizzare immagini e suoni, aggiungi gli ID risorse e Sorgente alla tua tabella di Localizzazione. Le voci dell'ID risorsa nella tabella di Localizzazione deve includere una Chiave come identificatore da richiamare da parte dell'API. Di seguito è riportato un esempio di voce di una tabella di Localizzazione che utilizza gli ID della risorsa:

ChiaveFonteespt
Chiave_ImmagineGioielli295709360629570936712957093727

Il codice seguente sostituisce l'ID risorsa di un ImageLabelcon la risorsa ID spagnola fornita dalla tabella di Localizzazione:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
-- Local variables
local localizedImageID
local localizedImage = Instance.new("ImageLabel")
-- Load Translator for "es". Wrap the function within a pcall() to protect against failures.
local res, translator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync("es")
end)
if res then
-- Get asset ID from localization table by referencing the Key
localizedImageID = translator:FormatByKey("Key_JewelsImage")
-- Set the image
localizedImage.Image = "rbxassetid://" .. localizedImageID
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end

Traduzione di Singole Stringhe

In alcune situazioni, puoi puntare su singole stringhe individuali per la traduzione. Translator:Translate() può recuperare le singole voci sulla tabella di Localizzazione in base alla stringa di partenza.

Nell'esempio successivo, si utilizza la seguente voce di Localizzazione:

Fonteesespt
SchermoSchermo2950936712957093727

Il seguente Script stamperò la traduzione Spagnola dello "Schermo" nella finestra Output:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
-- Load Translator for "es". Wrap the function within a pcall() to protect against failures.
local res, translator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync("es")
end)
if res then
-- Use Translate function, providing object context and string
local sourceTranslation = translator:Translate(game, "Screen")
print(sourceTranslation) -- Expected Output: "Pantalla"
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end

Utilizzo delle Sovrascritture del Contesto

In alcuni casi la Stringa può avere più significati. Ad esempio, la parola "Schermo" può indicare sia uno schermo per computer che uno schermo per la finestra, ma le traduzioni spagnole sono completamente diverse.

La colonnaContesto della tabella di Localizzazione serve a specificare le traduzioni attraverso le sovrascritture del contesto. Specificare l'oggetto in-game nella tua tabella di Localizzazione come nell'esempio seguente:

ContestoFontees
workspace.WindowScreen.SurfaceGui.TextLabelSchermoMosquito
SchermoSchermo

Lo Script seguente utilizza una sovrascrittura del contesto per dare priorità a una traduzione specifica:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
-- Load Translator for "es". Wrap the function within a pcall() to protect against failures.
local res, translator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync("es")
end)
if res then
-- use Translate function, providing object context and string
local sourceTranslation = translator:Translate( workspace.WindowScreen.SurfaceGui.TextLabel, "Screen")
print(sourceTranslation) -- Expected Output: Mosquitero
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end

Contesti multipli

In caso di contesti multipli, il servizio di localizzazione confronta le relazioni tra gli oggetti nel campo Contesto da destra a sinistra, utilizzando la corrispondenza più vicina.

Ad esempio, una tabella di Localizzazione nella tua esperienza può avere le seguenti voci di stringhe di origine condivisa:

ContestoFontees
workspace.WindowScreen.SurfaceGui.TextLabelSchermoMosquito
playerGui.ScreenGui.TextButtonSchermoSchermo

Se la Stringa "Schermo" viene aggiunta a un playerGui.ScreenGui.TextLabel oggetto nella tua esperienza, il servizio di Localizzazione visualizza "Mosquitero" come traduzione spagnola che corrisponde al contesto più vicino.

Sostituzione dei Parametri

Quando si usano parametri per tradurre contenuti dinamici, imposta i valori su una tabella e trasmetti la tabella come argomento tramite API.

In questo esempio, l'esperienza ha una tabella di Localizzazione con le seguenti voci:

ChiaveFontees
Chiave_Premio_1{1:int} gioielli{1:int} joyas
Chiave_Premio_2${AmountCash:fixed} contanti e {NumJewels:intgioielli${AmountCash:fixed} dinero y {NumJewels:int joyas

Utilizza il seguente esempio di codice per tradurre queste stringhe con i valori dei parametri:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
-- Load Translator for "es". Wrap the function within a pcall() to protect against failures.
local res, translator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync("es")
end)
if res then
-- Set the parameter value in "Key_Prize_1" to 100
local keyTranslation1 = translator:FormatByKey("Key_Prize_1", {100})
print(keyTranslation1) -- Expected Output: 100 joyas
-- Set multiple parameters to 500 and 100 by name
local keyTranslation2 = translator:FormatByKey("Key_Prize_2", {AmountCash=500, NumJewels=100})
print(keyTranslation2) -- Expected Output: $500.00 dinero y 100 joyas
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end

Cambio di Lingua

In alcuni casi, potrai voler visualizzare le traduzioni di altre lingue nella tua esperienza. In alcuni casi, potrai voler visualizzare le traduzioni di altre lingue nella tua esperienza Puoi impostare il nuovo traduttore con un codice di Paese diverso usandoLocalizationService:GetTranslatorForLocaleAsync().

Il seguente esempio di codice imposta un traduttore con un codice paese manuale e un traduttore aggiuntivo basato sulle impostazioni locali globali dell'utente:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
local Players = game:GetService("Players")
-- Local variables
local player = Players.LocalPlayer
-- Load Translator for "pt". Wrap translator functions within a pcall() to protect against failures.
local res1, translator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync("pt")
end)
-- Load second Translator with Player's locale, in this example "es"
local res2, fallbackTranslator = pcall(function()
return LocalizationService:GetTranslatorForPlayerAsync(player)
end)
-- Use Translate function with first Translator
if res1 then
local translate1 = translator:Translate(game, "jewels")
print(translate1) -- Expected Output in pt: joyas
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end
-- Use Translate function with second Translator
if res2 then
local translate2 = fallbackTranslator:Translate(game, "jewels")
print(translate2) -- Expected Output in if user is set to 'es': jóias
else
print('GetTranslatorForPlayerAsync failed: ' .. fallbackTranslator)
end

Reazione agli Utenti che cambiano Lingua

Gli Utenti possono modificare le impostazioni della lingua in qualsiasi momento utilizzando il menu Impostazioni in-experience. Questa notifica alla configurazione dell'utente aggiorna automaticamente le risorse di localizzazione non scripting, come le stringhe da traduzione automatica, ma potrebbe non aggiornare le modifiche di Localizzazione scriptate che sono già state riprodotte, come le immagini e i suoni dell'Interfaccio grafica utente.

Impostazione della Lingua In-Experience
Gli Utenti possono impostare le lingue disponibili nell'esperienza

Per assicurarsi che le risorse localizzate da script vengano aggiornate correttamente, ascolta l' GetPropertyChangedSignal evento per le modifiche di Proprietà dell'ID Locale Translator dell'esempiorestituito daLocalizationService.GetTranslatorForPlayerAsync . Quando si usano LocalizationService.GetTranslatorForPlayerAsync, avvolgi la funzione all'interno di un pcall in caso di errori.

Il seguente esempio di codice stampa l'ID di localizzazione dell'utente e l'ID di localizzazione dell'esempio del Traduttore per l'utente quando l'utente cambia le lingue:


local LocalizationService = game:GetService("LocalizationService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- If GetTranslatorForPlayerAsync succeeds, it will return a Translator for player's current locale
local res, translator = pcall(function()
return LocalizationService:GetTranslatorForPlayerAsync(player)
end)
-- Function that gets called when change in player's locale ID is detected
local function OnLocaleIdChanged()
print("Translator has changed to: " .. translator.LocaleId)
-- You should re-translate any assets translated with Localization APIs to the player's new language here
end
-- Check if GetTranslatorForPlayerAsync succeeded
if res then
-- If succeeded, translate assets here using translator
-- Listen for a change in player's locale ID
translator:GetPropertyChangedSignal("LocaleId"):Connect(OnLocaleIdChanged)
else
print('GetTranslatorForPlayerAsync failed: ' .. translator)
end

Creare un Modulo di TranslationHelper

Quando carichi i traduttori in base alla localizzazione preferita del giocatore, puoi riutilizzare il codice. Per riutilizzare il codice, Imposta un elemento di aiuto ModuleScriptche carica in modo sicuro i traduttori in base alla localizzazione predefinita del giocatore e include funzioni per fornire traduzioni e cambiare la lingua.

Il seguete esempio di codice implementa un TranslationHelper che puoi copiare nel tuo progetto come un ModuleScript in ReplicatedStorage:


local TranslationHelper = {}
local LocalizationService = game:GetService("LocalizationService")
local Players = game:GetService("Players")
-- Local variables
local player = Players.LocalPlayer
local sourceLanguageCode = "en"
-- Get translators
local playerTranslator, fallbackTranslator
local foundPlayerTranslator = pcall(function()
playerTranslator = LocalizationService:GetTranslatorForPlayerAsync(player)
end)
local foundFallbackTranslator = pcall(function()
fallbackTranslator = LocalizationService:GetTranslatorForLocaleAsync(sourceLanguageCode)
end)
-- Create a method TranslationHelper.setLanguage to load a new translation for the TranslationHelper
function TranslationHelper.setLanguage(newLanguageCode)
if sourceLanguageCode ~= newLanguageCode then
local success, newPlayerTranslator = pcall(function()
return LocalizationService:GetTranslatorForLocaleAsync(newLanguageCode)
end)
--Only override current playerTranslator if the new one is valid (fallbackTranslator remains as experience's source language)
if success and newPlayerTranslator then
playerTranslator = newPlayerTranslator
return true
end
end
return false
end
-- Create a Translate function that uses a fallback translator if the first fails to load or return successfully. You can also set the referenced object to default to the generic game object
function TranslationHelper.translate(text, object)
if not object then
object = game
end
local translation = ""
local foundTranslation = false
if foundPlayerTranslator then
return playerTranslator:Translate(object, text)
end
if foundFallbackTranslator then
return fallbackTranslator:Translate(object, text)
end
return false
end
-- Create a FormatByKey() function that uses a fallback translator if the first fails to load or return successfully
function TranslationHelper.translateByKey(key, arguments)
local translation = ""
local foundTranslation = false
-- First tries to translate for the player's language (if a translator was found)
if foundPlayerTranslator then
foundTranslation = pcall(function()
translation = playerTranslator:FormatByKey(key, arguments)
end)
end
if foundFallbackTranslator and not foundTranslation then
foundTranslation = pcall(function()
translation = fallbackTranslator:FormatByKey(key, arguments)
end)
end
if foundTranslation then
return translation
else
return false
end
end
return TranslationHelper

Quando il modulo è in ReplicatedStorage, richiedilo da unaLocalScript per richiamare le funzioni del modulo. Il seguente codice utilizza la funzione di questo modulo per tradurre una singola stringa:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Require translation module
local TranslationHelper = require(ReplicatedStorage:WaitForChild("TranslationHelper"))
-- Use the functions provided in TranslationHelper
TranslationHelper.setLanguage("es")
local sourceTranslation = TranslationHelper.translate("Screen")
print(sourceTranslation) -- Expected Output in 'es': "Pantalla"