Unity - 记录打包成android,处理应用名多语言

Unity版本:2019.4.5f1,本文实现的多语言为简体中文,繁体中文

前言:

如下图所示,在PlayerSettings里面只能设置基础的应用名;


下面记录我在Unity打包成android时,实现应用名的本地化的过程:

方式一(未成功):在Assets/Plugins/Android/目录下添加res

首先要了解,我们配置的默认应用名在导成android时会在src→main→res→values目录下生成strings.xml文件



strings.xml文件内容如下:



    My Game

因此,我们只需要依照android多语言的方式,在src→main→res目录下添加:values-zh-rCN,values-zh-rTW(我这里只添加繁体和简体中文,更多语言请自行查找android的对应语言代码),并分别创建strings.xml文件,内容如下:

  • values-zh-rCN


    我的游戏

  • values-zh-rTW


    我的遊戲

在unity工程中,我们只需要Plugins→Android目录下创建res目录,其里面内容如下:



如此之后打包确并没有成功,并有如下警告信息:

OBSOLETE - Providing Android resources in Assets/Plugins/Android/res is deprecated, please move your resources to an AAR or an Android Library. 
See "AAR plug-ins and Android Libraries" section of the Manual for more details.
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun() (at /Users/builduser/buildslave/unity/build/Editor/Mono/BuildPlayerWindow.cs:136)

由该警告可知,直接添加 Assets/Plugins/Android/res的方式已经被放弃了,需要打包成aar,由此引出方式二。
参考链接:Unity Android应用名称的国际化

方式二:打包res到aar

这一步需要了解较多android知识,这里简要描述下:
1.创建android工程,添加module
2.在module的创建values-zh-rCN,values-zh-rTW目录和语言文件
3.将module打包成aar
4.将aar拷贝到Assets/Plugins/Android/目录下

我在项目中使用了I2 Localization实现多语言,当时没有了解I2 Localization机制,和其产生了冲突,导致部分语言未生效

方式三:在Assets/Plugins/Android/目录下添加res,同时在 build.gradle使用task

1.添加res目录(过程同方法一)
2.在Bulid Settings → Player Settings → Android → Publishing Settings 中勾选Custom Launcher Gradle Templ:


image.png

3.在生成的launcherTemplate.gradle文件末尾添加如下代码(使用task在编译时将前面添加的res目录复制到正确的地址):

task localizeAppName(type: Copy) {
    from("${project.rootDir}/unityLibrary/unity-android-resources/res/") {
        include "**"
    }
    into "${project.projectDir}/src/main/res/"
}

preBuild.dependsOn(localizeAppName)

同样由于使用了I2 Localization,导致部分语言未生效,这里可以通过类似如下的代码删除I2 Localization生成的strings.xml文件:
注意: 1.我这里只针对自己项目移除了简体中文和繁体中文
         2.如果strings.xml未能成功移除,在需要将工程导出成Android项目,找到正确的文件路径进行移除

/* 删除自动生成的多余values-zh-rCN */
task appNameDeleteCN(type: Delete) {
    delete "${project.projectDir}/src/main/res/values-zh-rCN/strings.xml"
    delete "${project.projectDir}/src/main/res/values-zh-rTW/strings.xml"
}

preBuild.dependsOn(appNameDeleteCN)

参考链接:Unity2018 设置 Android 程序名称的多语言

方式四:参考I2 Localization,在unity中动态生成strings.xml

这里不多赘述了,直接贴出其PostProcessBuild_Android类

#if UNITY_ANDROID
using UnityEditor.Callbacks;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace I2.Loc
{
   public class PostProcessBuild_Android
   {
        // Post Process Scene is a hack, because using PostProcessBuild will be called after the APK is generated, and so, I didn't find a way to copy the new files
        [PostProcessScene]
        public static void OnPostProcessScene()
        {
            #if UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
                bool isFirstScene = (EditorBuildSettings.scenes.Length>0 && EditorBuildSettings.scenes[0].path == EditorApplication.currentScene);
            #else
                bool isFirstScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex <= 0;
            #endif

            if (!EditorApplication.isPlayingOrWillChangePlaymode &&
                (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android) &&
                isFirstScene)
            {
                string projPath = System.IO.Path.GetFullPath(Application.streamingAssetsPath + "/../../Temp/StagingArea");
                //string projPath = System.IO.Path.GetFullPath(Application.dataPath+ "/Plugins/Android");
                PostProcessAndroid(BuildTarget.Android, projPath);
            }
        }

        //[PostProcessBuild(10000)]
        public static void PostProcessAndroid(BuildTarget buildTarget, string pathToBuiltProject)
      {
         if (buildTarget!=BuildTarget.Android)
            return;

            if (LocalizationManager.Sources.Count <= 0)
            LocalizationManager.UpdateSources();

            // Get language with variants, but also add it without the variant to allow fallbacks (e.g. en-CA also adds en)
         var langCodes = LocalizationManager.GetAllLanguagesCode(false).Concat( LocalizationManager.GetAllLanguagesCode(true) ).Distinct().ToList();

         if (langCodes.Count <= 0)
            return;
         string stringXML =  "\n"+
                        "\n"+
                        "    {0}\n"+
                        "";

            SetStringsFile( pathToBuiltProject+"/res/values", "strings.xml", stringXML, LocalizationManager.GetAppName(langCodes[0]) );


         var list = new List();
         list.Add( pathToBuiltProject + "/res/values" );
         foreach (var code in langCodes)
         {
                // Android doesn't use zh-CN or zh-TW, instead it uses: zh-rCN, zh-rTW, zh
                string fixedCode = code;
                if (fixedCode.StartsWith("zh", System.StringComparison.OrdinalIgnoreCase))
                {
                    string googleCode = GoogleLanguages.GetGoogleLanguageCode(fixedCode);
                    if (googleCode==null) googleCode = fixedCode;
                    fixedCode = (googleCode == "zh-CN") ? "zh-CN" : googleCode;
                }
            fixedCode = fixedCode.Replace("-", "-r");

                string dir = pathToBuiltProject + "/res/values-" + fixedCode;

                SetStringsFile( dir, "strings.xml", stringXML, LocalizationManager.GetAppName(code) );
         }
      }

      static void CreateFileIfNeeded ( string folder, string fileName, string text )
      {
         try
         {
            if (!System.IO.Directory.Exists( folder ))
               System.IO.Directory.CreateDirectory( folder );

            if (!System.IO.File.Exists( folder + "/"+fileName ))
               System.IO.File.WriteAllText( folder + "/"+fileName, text );
         }
         catch (System.Exception e)
         {
            Debug.Log( e );
         }
      }

        static void SetStringsFile(string folder, string fileName, string stringXML, string appName)
        {
            try
            {
                appName = appName.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", "\\\"").Replace("'", "\\'");
                appName = appName.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);

                if (!System.IO.Directory.Exists(folder))
                    System.IO.Directory.CreateDirectory(folder);

                if (!System.IO.File.Exists(folder + "/" + fileName))
                {
                    // create the string file if it doesn't exist
                    stringXML = string.Format(stringXML, appName);
                }
                else
                {
                    stringXML = System.IO.File.ReadAllText(folder + "/" + fileName);
                    // find app_name
                    var pattern = "\"app_name\">(.*)<\\/string>";
                    var regexPattern = new System.Text.RegularExpressions.Regex(pattern);
                    if (regexPattern.IsMatch(stringXML))
                    {
                        // Override the AppName if it was found
                        stringXML = regexPattern.Replace(stringXML, string.Format("\"app_name\">{0}", appName));
                    }
                    else
                    {
                        // insert the appName if it wasn't there
                        int idx = stringXML.IndexOf("");
                        if (idx > 0)
                            stringXML = stringXML.Insert(idx + "".Length, string.Format("\n    {0}\n", appName));
                    }
                }
                System.IO.File.WriteAllText(folder + "/" + fileName, stringXML);
            }
            catch (System.Exception e)
            {
                Debug.Log(e);
            }
        }
    }
}
#endif

你可能感兴趣的:(Unity - 记录打包成android,处理应用名多语言)