Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Last active January 31, 2025 18:25
Show Gist options
  • Save grimmdev/979877fcdc943267e44c to your computer and use it in GitHub Desktop.
Save grimmdev/979877fcdc943267e44c to your computer and use it in GitHub Desktop.
Translate method/api using Unity 3D. Completely Free with no Restrictions, by using Google's Internal API, we cut out the need for any api keys.
// We need this for parsing the JSON, unless you use an alternative.
// You will need SimpleJSON if you don't use alternatives.
// It can be gotten hither. http://wiki.unity3d.com/index.php/SimpleJSON
using SimpleJSON;
using UnityEngine;
using System.Collections;
public class Translate : MonoBehaviour {
// Should we debug?
public bool isDebug = false;
// Here's where we store the translated text!
private string translatedText = "";
// This is only called when the scene loads.
void Start () {
// Strictly for debugging to test a few words!
if(isDebug)
StartCoroutine (Process ("en","Bonsoir."));
}
// We have use googles own api built into google Translator.
public IEnumerator Process (string targetLang, string sourceText) {
// We use Auto by default to determine if google can figure it out.. sometimes it can't.
string sourceLang = "auto";
// Construct the url using our variables and googles api.
string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ sourceLang + "&tl=" + targetLang + "&dt=t&q=" + WWW.EscapeURL(sourceText);
// Put together our unity bits for the web call.
WWW www = new WWW (url);
// Now we actually make the call and wait for it to finish.
yield return www;
// Check to see if it's done.
if (www.isDone) {
// Check to see if we don't have any errors.
if(string.IsNullOrEmpty(www.error)){
// Parse the response using JSON.
var N = JSONNode.Parse(www.text);
// Dig through and take apart the text to get to the good stuff.
translatedText = N[0][0][0];
// This is purely for debugging in the Editor to see if it's the word you wanted.
if(isDebug)
print(translatedText);
}
}
}
// Exactly the same as above but allow the user to change from Auto, for when google get's all Jerk Butt-y
public IEnumerator Process (string sourceLang, string targetLang, string sourceText) {
string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ sourceLang + "&tl=" + targetLang + "&dt=t&q=" + WWW.EscapeURL(sourceText);
WWW www = new WWW (url);
yield return www;
if (www.isDone) {
if(string.IsNullOrEmpty(www.error)){
var N = JSONNode.Parse(www.text);
translatedText = N[0][0][0];
if(isDebug)
print(translatedText);
}
}
}
}
@barzorke
Copy link

barzorke commented Sep 4, 2017

Thank you very much for this code !
I did change it myself to make it an external usable API for all my code

Here is the code

// Credit goes to Grimmdev https://gist.github.com/grimmdev/979877fcdc943267e44c

// We need this for parsing the JSON, unless you use an alternative.
// You will need SimpleJSON if you don't use alternatives.
// It can be gotten hither. http://wiki.unity3d.com/index.php/SimpleJSON
using SimpleJSON;
using UnityEngine;
using System.Collections;

public class Translate
{
    // We have use googles own api built into google Translator.
    public static IEnumerator Process(string targetLang, string sourceText, System.Action<string> result)
    {
        yield return Process("auto", targetLang, sourceText, result);
    }

    // Exactly the same as above but allow the user to change from Auto, for when google get's all Jerk Butt-y
    public static IEnumerator Process(string sourceLang, string targetLang, string sourceText, System.Action<string> result)
    {
        string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
            + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + WWW.EscapeURL(sourceText);

        WWW www = new WWW(url);
        yield return www;

        if (www.isDone)
        {
            if (string.IsNullOrEmpty(www.error))
            {
                var N = JSONNode.Parse(www.text);
                string translatedText = N[0][0][0];

                result(translatedText);
            }
        }
    }
}

@olivierchatagnon
Copy link

olivierchatagnon commented Oct 20, 2017

To fix issue in this case of long sentence truncated like this:
"This template allow you to be sure to not have translation to do in any languages.
Typically for hard coded values like "true", "false", "1", "0"...
We advise you to use a category restriction in this case in order to keep this status during export."
I replace
string translatedText = N[0][0][0];
by
for (int i = 0; (i < TableReturned[0].Count); i++) tranlatedText.Append((string)TableReturned[0][i][0]);

Here the complete code:

        public static string TranslateGoogleApisSimple(string InitialText, string fromCulture, string toCulture)
        {
            string textToSearch = InitialText;
            string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}", fromCulture, toCulture, HttpUtility.UrlEncode(textToSearch));
            string responseText = "Not Set";
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                using (System.Net.HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    var encoding = ASCIIEncoding.UTF8;
                    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
                    {
                        string text = reader.ReadToEnd();
                        //Found JSON parse on https://gist.github.com/grimmdev/979877fcdc943267e44c
                        var TableReturned = JSONNode.Parse(text);
                        StringBuilder tranlatedText = new StringBuilder();
                        if (TableReturned[0].Count > 1)
                            text = "";
                        for (int i = 0; (i < TableReturned[0].Count); i++)
                            tranlatedText.Append((string)TableReturned[0][i][0]);

                        responseText = tranlatedText.ToString();
                    }
                }

            }
            catch (Exception ex)
            {
                responseText = string.Format("Translation Error with GoogleAPI: {0}\r\nUrl:{1}", ex.Message, url);
            }
            return responseText;
        }

@uberbax
Copy link

uberbax commented Dec 7, 2017

Hi, guys ! It works well with languages like deutsch and french, but works bad with russian. For example "Привет." which should be equivalent for "Hello." - we have "DYN € ивÐμÑ,." for "auto" sourceLang and "РџСЂРёРІРμС,." for "ru". Can u please look into that issue and what may cause such behaviour, thank you.

@alarm656
Copy link

Hi, guys ! It works well with languages like deutsch and french, but works bad with russian. For example "Привет." which should be equivalent for "Hello." - we have "DYN € ивÐμÑ,." for "auto" sourceLang and "РџСЂРёРІРμС,." for "ru". Can u please look into that issue and what may cause such behaviour, thank you.

You need change the font

@WindyYam
Copy link

WindyYam commented Mar 5, 2020

For those who are willing to make it work in Android, according to https://www.codeproject.com/Articles/12711/Google-Translator, a user-agent head should be added in order not to redirect to captcha
with UnityWebRequest, add uwr.SetRequestHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36") before uwr.SendWebRequest()

@Zetjen
Copy link

Zetjen commented Sep 2, 2020

Hi, i upgrade the code to the UnityWebRequest to remove the debugging warnings.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SimpleJSON;
using UnityEngine.Networking;
public class Translator : MonoBehaviour
{
	// Should we debug?
	public bool isDebug = false;
	// Here's where we store the translated text!
	private string translatedText = "";

	// This is only called when the scene loads.
	void Start()
	{
		// Strictly for debugging to test a few words!
		if (isDebug)
			StartCoroutine(Process("es", "all this code is working!"));
	}

	// We have use googles own api built into google Translator.
	public IEnumerator Process(string targetLang, string sourceText)
	{
		// We use Auto by default to determine if google can figure it out.. sometimes it can't.
		string sourceLang = "auto";
		// Construct the url using our variables and googles api.
		string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
			+ sourceLang + "&tl=" + targetLang + "&dt=t&q=" + UnityWebRequest.EscapeURL(sourceText);

		using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
		{
			// Request and wait for the desired page.
			yield return webRequest.SendWebRequest();

			// Check to see if we don't have any errors.
			if (string.IsNullOrEmpty(webRequest.error))
			{
				// Parse the response using JSON.
				var N = JSONNode.Parse(webRequest.downloadHandler.text);
				// Dig through and take apart the text to get to the good stuff.
				translatedText = N[0][0][0];
				// This is purely for debugging in the Editor to see if it's the word you wanted.
				if (isDebug)
					print(translatedText);
			}
		}
	}

	// Exactly the same as above but allow the user to change from Auto, for when google get's all Jerk Butt-y
	public IEnumerator Process(string sourceLang, string targetLang, string sourceText)
	{
		string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
			+ sourceLang + "&tl=" + targetLang + "&dt=t&q=" + UnityWebRequest.EscapeURL(sourceText);

		using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
		{
			// Request and wait for the desired page.
			yield return webRequest.SendWebRequest();

			// Check to see if we don't have any errors.
			if (string.IsNullOrEmpty(webRequest.error))
			{
				// Parse the response using JSON.
				var N = JSONNode.Parse(webRequest.downloadHandler.text);
				// Dig through and take apart the text to get to the good stuff.
				translatedText = N[0][0][0];
				// This is purely for debugging in the Editor to see if it's the word you wanted.
				if (isDebug)
					print(translatedText);
			}
		}
	}
}

@Mayama333
Copy link

-The translation stops working-
Hi, I'm using this translation method
I have the problem that translating 3 or 5 times a number of random lines stops working and I don't get any more results.
Can someone tell me if the same thing happens and what could be the problem?
I don't get any errors and debugs work fine.

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