跳到正文
Qiita · Unity 开发社区· 来源· HatomeGames·· 1 小时前AI 评分35

Unity 开发者制作 Localization 扩展以从外部文件导入翻译数据

【Unity】外部ファイルから翻訳データを取り込めるUnityのLocalization拡張作った

正文 · AI 翻译

前言

Unity 的 Localization 包基本上假设开发者基于预先准备的表格进行本地化。
另一方面,作为游戏开发者,有时也希望将自身无法掌握的语言的支持工作委托给社区。

在本文中,我将介绍一个系统:通过挂钩 Localization 包提供的 ITableProvider,能够从外部文件导入翻译数据。

前提条件

Unity 2023.2.22f1
UniRx 7.1.0
UniTask 2.5.10

実装方針

在打开语言选择下拉菜单时,读取指定目录下的 json 文件;在下拉菜单关闭时,仅缓存所选语言的翻译数据。
通过继承 ITableProvider 的类 ExternalJsonTableProvider,当 Unity 端请求翻译数据时,原本应引用 Addressables 的地方改为路由到已缓存的翻译数据。
要将 ExternalJsonTableProvider 注册到 LocalizationEditorSettings,需使用编辑器扩展。

完成品

image.gif

代码(部分摘录)

项目的完整内容请参考上述仓库。
请注意,它重度依赖 UniRx 和 UniTask。

  • ExternalJsonTableProvider.cs
    这是本次的核心部分。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization.Tables;
using UnityEngine.ResourceManagement.AsyncOperations;

[Serializable]
public class ExternalLanguageMeta
{
    public string AnglicizedName;
    public string NativeName;
    public string LocaleCode;
    public string UnityVersion;
    public string GameVersion;
    public int FormatVersion;
    public string DisplayName;
    public string Author;
    public string Note;
}

[Serializable]
public class ExternalLanguageData
{
    public ExternalLanguageMeta Meta;
    public Dictionary<string, string> Entries;

    public ExternalLanguageData() { }

    public ExternalLanguageData(StringTable stringTable)
    {
        Entries = new();
        foreach (var entry in stringTable.Values)
        {
            Entries[entry.Key] = entry.Value;
        }
        Meta = new ExternalLanguageMeta
        {
            AnglicizedName = "For example, \"German\"",
            NativeName = "For example, \"Deutsch\"",
            LocaleCode = stringTable.LocaleIdentifier.Code,
            UnityVersion = Application.unityVersion,
            GameVersion = Application.version,
            FormatVersion = GameManager.LANG_FORMAT_VERSION,
            DisplayName = "Language File Template",
            Author = "Enter your name here.",
            Note = "Do not modify keys. Keep placeholders like {0} or {name} ."
        };
    }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented);
    }
}

public class ExternalLanguageFile
{
    public ExternalLanguageData Data;
    public string FileName;
    public string Path;
    public Locale Locale;
}

[Serializable]
public class ExternalJsonTableProvider : ITableProvider
{
    const string TABLE_COLLECTION_NAME = "StringTable";

    static readonly Dictionary<Locale, ExternalLanguageFile> externalLanguageFiles = new(new LocaleReferenceComparer());

    public static void SetExternalLanguageFiles(IEnumerable<ExternalLanguageFile> files)
    {
        externalLanguageFiles.Clear();
        foreach (var file in files)
            externalLanguageFiles.Add(file.Locale, file);
    }

    public static void RetainExternalLanguageFile(Locale locale)
    {
        if (locale == null)
        {
            externalLanguageFiles.Clear();
            return;
        }

        var localesToRemove = new List<Locale>();
        foreach (var registeredLocale in externalLanguageFiles.Keys)
        {
            if (!ReferenceEquals(registeredLocale, locale))
                localesToRemove.Add(registeredLocale);
        }

        foreach (var registeredLocale in localesToRemove)
            externalLanguageFiles.Remove(registeredLocale);
    }

    public AsyncOperationHandle<TTable> ProvideTableAsync<TTable>(string tableCollectionName, Locale locale) where TTable : LocalizationTable
    {
        if (typeof(TTable) != typeof(StringTable) || tableCollectionName != TABLE_COLLECTION_NAME || locale == null) return default;

        if (!externalLanguageFiles.TryGetValue(locale, out var languageFile)) return default;

        string path = languageFile.Path;
        ExternalLanguageData languageData = languageFile.Data;

        if (languageData?.Entries == null)
            return CreateFailedOperation<TTable>($"Language file '{path}' does not contain an Entries object.");

        if (!string.IsNullOrEmpty(languageData.Meta?.LocaleCode) &&
            !string.Equals(languageData.Meta.LocaleCode, locale.Identifier.Code, StringComparison.OrdinalIgnoreCase))
        {
            return CreateFailedOperation<TTable>($"LocaleCode '{languageData.Meta.LocaleCode}' in '{path}' does not match '{locale.Identifier.Code}'.");
        }

        Locale sourceLocale = LocalizationSettings.ProjectLocale;
        if (sourceLocale == null) return CreateFailedOperation<TTable>("LocalizationSettings.ProjectLocale is not set.");

        string sourceAddress = $"{tableCollectionName}_{sourceLocale.Identifier.Code}";
        AsyncOperationHandle<StringTable> sourceHandle = Addressables.LoadAssetAsync<StringTable>(sourceAddress);

        var tableHandle = Addressables.ResourceManager.CreateChainOperation(sourceHandle,
            operation =>
            {
                if (operation.Status != AsyncOperationStatus.Succeeded || operation.Result == null)
                    return CreateFailedOperation<TTable>($"Failed to load source StringTable '{sourceAddress}'.");

                return CreateTableOperation<TTable>(operation.Result, locale, languageData, path);
            });

        // The chain owns its dependency now; release the handle created by this provider.
        Addressables.Release(sourceHandle);
        return tableHandle;
    }

    static AsyncOperationHandle<TTable> CreateTableOperation<TTable>(
        StringTable sourceTable,
        Locale locale,
        ExternalLanguageData languageData,
        string path)
        where TTable : LocalizationTable
    {
        if (sourceTable.SharedData == null)
            return CreateFailedOperation<TTable>($"Source StringTable '{sourceTable.name}' has no SharedTableData.");

        var table = ScriptableObject.CreateInstance<StringTable>();
        table.name = $"{TABLE_COLLECTION_NAME}_{locale.Identifier.Code}";
        table.SharedData = UnityEngine.Object.Instantiate(sourceTable.SharedData);
        table.LocaleIdentifier = locale.Identifier;

        foreach (var sourceEntry in sourceTable.Values)
        {
            var entry = table.AddEntry(sourceEntry.Key, sourceEntry.Value);
            entry.IsSmart = sourceEntry.IsSmart;
        }

        foreach (var translation in languageData.Entries)
        {
            if (table.SharedData.GetId(translation.Key) == 0)
            {
                Debug.LogWarning($"Ignoring unknown localization key '{translation.Key}' in '{path}'.");
                continue;
            }

            var entry = table.GetEntry(translation.Key) ?? table.AddEntry(translation.Key, translation.Value);
            entry.Value = translation.Value;
        }

        var localizedTable = (TTable)(LocalizationTable)table;
        return Addressables.ResourceManager.CreateCompletedOperation(localizedTable, null);
    }

    static AsyncOperationHandle<TTable> CreateFailedOperation<TTable>(string error) where TTable : LocalizationTable
    {
        Debug.LogError(error);
        return Addressables.ResourceManager.CreateCompletedOperation<TTable>(null, error);
    }

    sealed class LocaleReferenceComparer : IEqualityComparer<Locale>
    {
        public bool Equals(Locale left, Locale right) => ReferenceEquals(left, right);
        public int GetHashCode(Locale locale) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(locale);
    }
}
  • LocalizationJsonApplier.cs
    这是一个将 ITableProvider 注册到 LocalizationEditorSettings 的编辑器扩展。
    另外还附带了输出外部翻译文件模板的功能。
using UnityEngine;
using UnityEditor;
using System.Linq;
using UnityEditor.Localization;
using System.IO;

public static class LocalizationJsonApplier
{
    [MenuItem("Tools/External Localization/Assign External Json Table Provider")]
    public static void AssignTableProvider()
    {
        GameIO.CreateFolderIfNeeded(GameIO.LanguagesFolderPath);

        var settings = LocalizationEditorSettings.ActiveLocalizationSettings;
        var stringDatabase = settings.GetStringDatabase();
        stringDatabase.TableProvider = new ExternalJsonTableProvider();
        stringDatabase.TablePostprocessor = null;

        var assetDatabase = settings.GetAssetDatabase();
        assetDatabase.TablePostprocessor = null;

        EditorUtility.SetDirty(settings);
        AssetDatabase.SaveAssets();
    }

    [MenuItem("Tools/External Localization/Export String Table to Json")]
    static void ExportPresetLanguages()
    {
        GameIO.CreateFolderIfNeeded(GameIO.LanguagesFolderPath);

        var stringTableCollections = AssetDatabase.FindAssets("t:StringTableCollection")
            .Select(guid => AssetDatabase.LoadAssetAtPath<StringTableCollection>(AssetDatabase.GUIDToAssetPath(guid))).FirstOrDefault();

        foreach (var stringTable in stringTableCollections.StringTables)
        {
            string json = new ExternalLanguageData(stringTable).ToJson();
            string path = $"{GameIO.LanguagesFolderPath}/{stringTable.LocaleIdentifier.Code}.lang";
            File.WriteAllText(path, json);
            Debug.Log($"String Table exported to: {path}");
        }
    }
}

实现过程中遇到的难点

  • ITablePostprocessor 不适合本次的用途
    ITablePostprocessor 似乎用于在加载表格后替换翻译等场景。
  • ITableProvider无法通过 GUI 注册到 LocalizationEditorSettings
    这是因为假定 ITableProvider 是可序列化的纯 C# 类。
    请从编辑器扩展中实例化 ITableProvider 并进行注册。
    取消注册大概可以通过赋值为 null 来实现。
  • 在Unity的Localization中,原则上每个Locale对应1个Table
    当存在不同译者对同一语言的翻译文件时,由于需要让两者都能被选择,这一限制就成了问题。
    如果对于外部翻译文件也能保证1Locale=1Table,那么实现应该能更简单一些。

结语

本文介绍了在Unity的Localization中实现从外部文件导入翻译数据的系统的方法。
希望对游戏开发有所帮助。

参考的网站

https://docs.unity3d.com/Packages/com.unity.localization@2.0/api/UnityEngine.Localization.Settings.ITableProvider.html
https://xrdnk.hateblo.jp/entry/localized_textmeshpro_font

0

转到点赞该内容的用户列表

0

注册为新用户,更便捷地使用Qiita

  1. 获取符合您需求的文章
  2. 高效回顾有用信息
  3. 可使用深色主题

注册后可执行的操作

来源:Qiita · Unity 开发社区 · qiita.com