Unity uses Google Translate to batch translate changed text

Record a small tool for batch translation of text changes by Google Translate. It supports batch modification of the Scene contained in BuildSettings and the Text text in all Prefabs in the resource. The principle is to use the API provided by Google Translate to replace and obtain strings at specific locations. To obtain the corresponding translation.
Note that to use EditorCoroutineUtility, you need to import the EditorCoroutine package from the PageManager first. The function is to use the coroutine under the editor.

using System;
using System.Collections;
using System.Text.RegularExpressions;
using Unity.EditorCoroutines.Editor;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.Networking;
using UnityEngine.UI;



public class Translator : MonoBehaviour
{
    
    
    private const string k_Url =
        "https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}";
    

    [MenuItem("ZWaveTools/TranslateText")]
    public static void Translate()
    {
    
    
    	//清空Console
        var logEntries = System.Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll");  
        var clearMethod = logEntries.GetMethod("Clear",System.Reflection.BindingFlags.Static | 	System.Reflection.BindingFlags.Public);  
        clearMethod.Invoke(null, null);
        
        EditorCoroutineUtility.StartCoroutineOwnerless(TranslateAsync());
    }

    public static IEnumerator TranslateAsync()
    {
    
    
        var scenes = EditorBuildSettings.scenes;
        foreach (var scene in scenes)
        {
    
    
            print("OpenNewScene");
            EditorSceneManager.OpenScene(scene.path);
            var tmpList1 = FindObjectsOfType<Text>(true);
            
            foreach (var tmp in tmpList1)
            {
    
    
                yield return TranslateAsync(tmp.text, ((targetText) =>
                {
    
    
                    print($"{
      
      tmp.text} {
      
      targetText}");
                    tmp.text = targetText;
                    EditorUtility.SetDirty(tmp);
                }));   
            }
            
            //var tmpList2 = FindObjectsOfType<TextMeshPro>(true);
            // foreach (var tmp in tmpList2)
            // {
    
    
            //     yield return EditorCoroutineUtility.StartCoroutineOwnerless(TranslateAsync(tmp.text, ((targetText) =>
            //     {
    
    
            //         print($"{tmp.text} {targetText}");
            //         //tmp.text = targetText;
            //         EditorUtility.SetDirty(tmp);
            //     })));
            // }
            
            EditorSceneManager.SaveOpenScenes();
            print("SaveOpenScene");
        }


        var guidList = AssetDatabase.FindAssets("t:Prefab");
        foreach (var guid in guidList)
        {
    
    
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var gameObject = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            var tmpList1 = gameObject.GetComponentsInChildren<Text>(true);
            
            foreach (var tmp in tmpList1)
            {
    
    
                yield return EditorCoroutineUtility.StartCoroutineOwnerless(TranslateAsync(tmp.text, ((targetText) =>
                {
    
    
                    print($"{
      
      gameObject.name} {
      
      tmp.text} {
      
      targetText}");
                    tmp.text = targetText;
                    EditorUtility.SetDirty(gameObject);
                })));
            }
            
            //var tmpList2 = gameObject.GetComponentsInChildren<TextMeshPro>(true);
            // foreach (var tmp in tmpList2)
            // {
    
    
            //     yield return EditorCoroutineUtility.StartCoroutineOwnerless(TranslateAsync(tmp.text, ((targetText) =>
            //     {
    
    
            //         print($"{gameObject.name} {tmp.gameObject.name}");
            //         print($"{tmp.text} {targetText}");
            //         tmp.text = targetText;
            //         EditorUtility.SetDirty(gameObject);
            //     })));
            // } 
        }
    }


    //更改sourceLang和targetLange对应的标识实现不同的翻译需求
    static IEnumerator TranslateAsync(string text, Action<string> complete, string sourceLang = "en", string targetLang = "zh-CN")
    {
    
    
        var requestUrl = string.Format(k_Url, sourceLang, targetLang, text);
        var request = UnityWebRequest.Get(requestUrl);
        request.timeout = 5;
        yield return request.SendWebRequest();

        if (string.IsNullOrEmpty(request.error))
        {
    
    
            var fullText = request.downloadHandler.text;
            print(fullText);
            Regex regex = new Regex("[/[][/[][/[]\"(.*?)\",");
            string targetText = regex.Match(fullText).Groups[1].ToString();
            complete(targetText);
        }

        yield return null;
    }
    
}

Refer to [Game Development Practical Practice] Unity calls Google Google’s free translation API (https interface). Young people don’t follow martial ethics. How do they speak in multiple languages?

Guess you like

Origin blog.csdn.net/weixin_44276280/article/details/131720754