はじめに
UnityのLocalizationパッケージは、基本的に開発者が事前に用意したテーブルを基にしたローカライズを想定しています。
一方でゲーム開発者としては、開発者自身が話せない言語への対応はコミュニティに委ねたいといったケースもあるかと思います。
本記事では、Localizationパッケージにて提供されるITableProviderをフックとして、外部ファイルから翻訳データを取り込めるようにするシステムを作ったので、それを紹介します。
前提条件
Unity 2023.2.22f1
UniRx 7.1.0
UniTask 2.5.10
実装方針
翻訳選択のドロップダウンを開いたときに特定ディレクトリ以下のjsonファイルを読み込み、ドロップダウンを閉じた際には選択した翻訳データのみをキャッシュするようにします。
ITableProviderを継承したクラスExternalJsonTableProviderにより、Unity側が翻訳データを要求したときに通常はAddressablesを参照するところを、キャッシュしておいた翻訳データにルーティングします。
ExternalJsonTableProviderをLocalizationEditorSettingsに登録するにはエディタ拡張を用います。
完成品
コード(一部抜粋)
プロジェクトの全容は上記のリポジトリを参照してください。
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がSerializableなpure C#クラスであることを想定されているためです。
エディタ拡張からITableProviderをインスタンス化して登録してください。
おそらく登録解除はnullを代入することで行えます。 - UnityのLocalizationでは原則1Localeにつき1Table
異なる翻訳者による同じ言語への翻訳ファイルが存在する場合、両方を選択可能にする必要があったため、この制約が問題になりました。
外部翻訳ファイルについても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
