Skip to content

Instantly share code, notes, and snippets.

@IJEMIN
Last active August 15, 2024 17:52
Show Gist options
  • Save IJEMIN/a48f8f302190044de05e3e3fea342fbd to your computer and use it in GitHub Desktop.
Save IJEMIN/a48f8f302190044de05e3e3fea342fbd to your computer and use it in GitHub Desktop.
Simple Unity Google Translator
/* Credit */
// Inspired by grimmdev's code - https://gist.github.com/grimmdev/979877fcdc943267e44c
/* Dependency */
// Import SimpleJSON Scripts : http://wiki.unity3d.com/index.php/SimpleJSON
// You can use your own JSON Parser if you want.
/* Limitations */
// translate.googleapis.com is free, but it only allows about 100 requests per one hour.
// After that, you will receive 429 error response.
// You may consider using paid service like google translate v2(https://translation.googleapis.com/language/translate/v2) to remove the limitations.
// Check here if you want to use paid version : https://gist.github.com/IJEMIN/fdff6db1b1131b91033cbf204247816e
using System;
using System.Collections;
using SimpleJSON;
using UnityEngine;
using UnityEngine.Networking;
public class GoogleTranslator : MonoBehaviour
{
private void Awake()
{
DoExample();
}
// Remove this method after understanding how to use.
private void DoExample()
{
TranslateText("en","ko","I'm a real gangster.", (success, translatedText) =>
{
if (success)
{
Debug.Log(translatedText);
}
});
TranslateText("ko","en","나는 리얼 갱스터다.", (success, translatedText) =>
{
if (success)
{
Debug.Log(translatedText);
}
});
}
public void TranslateText(string sourceLanguage, string targetLanguage, string sourceText, Action<bool, string> callback)
{
StartCoroutine(TranslateTextRoutine(sourceLanguage, targetLanguage, sourceText, callback));
}
private static IEnumerator TranslateTextRoutine(string sourceLanguage, string targetLanguage, string sourceText, Action<bool, string> callback)
{
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sourceLanguage}&tl={targetLanguage}&dt=t&q={UnityWebRequest.EscapeURL(sourceText)}";
var webRequest = UnityWebRequest.Get(url);
yield return webRequest.SendWebRequest();
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error);
callback.Invoke(false, string.Empty);
yield break;
}
var parsedTexts = JSONNode.Parse(webRequest.downloadHandler.text);
var translatedText = parsedTexts[0][0][0];
callback.Invoke(true, translatedText);
}
}
@NicholasBarrett98
Copy link

NicholasBarrett98 commented Mar 27, 2023

Thanks for sharing. I often use translators in my work. Google Translator is one of them. But I like https://www.translate.com/english-nepali better because it is always an accurate translation. They are ready to help with more than 90 languages and it's really true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment