Skip to main content

Translation Feature

UnityIcu provides a powerful AI-driven translation feature that supports over 200 languages, helping developers easily make their games global.


How to Use the Translation Feature

Follow these steps to understand and integrate UnityIcu's translation feature:

1. Generate Your API Key

  1. Log in to the UnityIcu platform.
  2. Navigate to Personal Center > Developer.
  3. Click Generate API Key.
  4. Copy the API Key to a secure location (e.g., a password manager or a private note).

Important: Never share your API Key with others. It is required for all interactions with the translation server, including map uploads and server communication. If compromised, it could lead to potential losses.


2. Obtain a usable dynamic translation address

Here is a Unity C# example demonstrating how to communicate with the UnityIcu translation server:

 // Dynamic URL Cache  
//The translation server requires significant interaction and real-time engagement. This is the first time we are calling to obtain a stable translation address, and it dynamically acquires the latest available address. If you don't want to go through this trouble, you can directly use this code to obtain the address and use it as a fixed address, but it's better to dynamically acquire it.
private static string _translateUrl;
private static bool _gettingUrl;

/// <summary>Retrieve from the central router during the first invocation /translate URL</summary>
private static async Task EnsureTranslateUrlAsync()
{
if (!string.IsNullOrEmpty(_translateUrl) || _gettingUrl) return;

_gettingUrl = true;
try
{
_translateUrl = await ServerRouterClient.GetServiceUrlAsync("translate");
Debug.Log($"[Router] translateUrl = {_translateUrl}");
}
catch (Exception ex)
{
Debug.LogError($"GET translateUrl ERROR: {ex.Message}");
throw;
}
finally { _gettingUrl = false; }
}
public static class ServerRouterClient
{
private static readonly HttpClient http = new() { Timeout = TimeSpan.FromSeconds(4) };
private const string RouterBase = "https://main.unity.icu"; // This is a tool designed to assist developers in automatically acquiring server terminals that are currently relatively idle
private const string Version = "0.1.6";//This is where the version number is obtained. It needs to be incremented based on version updates, and each version is unique

// Simple memory cache service -> url
private static readonly Dictionary<string, string> cache = new();

public static async Task<string> GetServiceUrlAsync(string service)
{
if (cache.TryGetValue(service, out var url))
return url;

string req = $"{RouterBase}/{service}?version={Version}";
using var resp = await http.GetAsync(req);
if (!resp.IsSuccessStatusCode)
throw new Exception($"Router {resp.StatusCode}");

var json = await resp.Content.ReadAsStringAsync();
var obj = JsonUtility.FromJson<ServerResponse>(json);
if (string.IsNullOrEmpty(obj.targetServer))
throw new Exception("Router returned empty targetServer");

cache[service] = obj.targetServer;
return obj.targetServer;
}

[Serializable] private class ServerResponse { public string targetServer; }
}


3. Translation API Integration

    /// <summary>Asynchronous translation</summary>
public static async Task<string> GetTranslationAsync(string text, string tgtLang)
{
if (string.IsNullOrEmpty(text)) return "";

if (text.Length > MaxTextLength)
{
Debug.LogError($"Text too long, >{MaxTextLength} chars");
return "[ERR-LONG]";
}

await EnsureTranslateUrlAsync();
if (string.IsNullOrEmpty(_translateUrl))
return text; // The URL is still unavailable, so we will use the original text directly

var requestBody = new
{
text,
tgt_lang = tgtLang,
apikey = ApiKey
};

string json = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");

try
{
var resp = await HttpClient.PostAsync(_translateUrl, content);
resp.EnsureSuccessStatusCode();

var respStr = await resp.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TranslationResponse>(respStr);

return result?.translation ?? text; // If parsing fails, revert to the original text
}
/*--------------------------------------------------------------------------------------------------------------------
New branch: Clear _translateUrl when a network/connection error occurs,
Let the next call retrieve the address from the central router again
--------------------------------------------------------------------------------------------------------------------*/
catch (HttpRequestException ex)
{
Debug.LogWarning($"Translation failed (network exception):{ex.Message}");
_translateUrl = null; // Key: Clear the cache immediately
return text; // Return to the original text first, without interrupting the plot
}
/* Other exceptions (such as deserialization) remain handled as they are */
catch (Exception ex)
{
Debug.LogWarning($"Translation failed:{ex.Message}");
return text;
}
}

private class TranslationResponse { public string translation; }

4.Example Usage

Below is a simple example of how to call the method above:

// Directly call the asynchronous translation method
string translatedText = await LanguageWebsocketSyc.GetTranslationAsync (currentLine, "en");

4. Additional Learning Resources

Refer to the Demo projects and documentation provided by UnityIcu to learn more about the usage of the translation feature and best practices.