XUnity.AutoTranslator:Unity游戏运行时自动翻译引擎架构设计与实现原理
XUnity.AutoTranslator:Unity游戏运行时自动翻译引擎架构设计与实现原理
【免费下载链接】XUnity.AutoTranslator项目地址: https://gitcode.com/gh_mirrors/xu/XUnity.AutoTranslator
XUnity.AutoTranslator是一款开源的高性能Unity游戏运行时自动翻译引擎,为游戏开发者提供了一套完整的本地化解决方案。该项目通过创新的运行时文本检测与替换机制,实现了对Unity游戏的多语言支持,无需修改游戏源码即可完成深度本地化集成。
核心技术架构概览
XUnity.AutoTranslator采用模块化分层架构设计,核心系统分为翻译引擎、资源重定向、插件适配和翻译服务四大模块。整个架构基于C# .NET框架构建,充分利用了Unity的反射机制和Hook技术,实现了对游戏运行时文本内容的智能捕获与替换。
核心模块架构
src/XUnity.AutoTranslator.Plugin.Core/ ; 核心翻译引擎 ├── Endpoints/ ; 翻译服务接口抽象层 ├── Hooks/ ; Unity组件钩子系统 ├── Text/ ; 文本处理与缓存管理 ├── UI/ ; 用户界面重定向 ├── UIResize/ ; UI自适应调整 ├── AssetRedirection/ ; 资源重定向系统 ├── Configuration/ ; 配置管理系统 └── Utilities/ ; 工具类库 src/Translators/ ; 翻译服务实现层 ├── GoogleTranslate/ ; Google翻译集成 ├── BaiduTranslate/ ; 百度翻译API集成 ├── DeepLTranslate/ ; DeepL专业翻译 ├── BingTranslate/ ; 必应翻译服务 └── CustomTranslate/ ; 自定义翻译接口 src/XUnity.ResourceRedirector/ ; 资源重定向核心 ├── Hooks/ ; Unity资源加载Hook ├── Async/ ; 异步资源处理 └── Contexts/ ; 资源上下文管理运行时文本捕获与替换机制
多框架文本组件支持
XUnity.AutoTranslator支持多种Unity文本渲染框架的Hook机制:
// 核心文本组件Hook接口 public interface ITextComponentHook { bool CanHandle(GameObject gameObject); void HookTextComponent(Component component); void UnhookTextComponent(Component component); } // UGUI文本组件Hook实现 public class UGUITextHook : ITextComponentHook { public void HookTextComponent(Component component) { var text = component as Text; if (text != null) { // 通过反射修改文本属性 var originalText = text.text; var translatedText = _cache.TryGetTranslation(originalText); if (translatedText != null) { text.text = translatedText; } } } }智能缓存系统设计
项目的文本翻译缓存系统采用多层缓存策略,确保翻译效率和内存优化:
public class TextTranslationCache : IReadOnlyTextTranslationCache { // 静态翻译字典(预加载) private Dictionary<string, string> _staticTranslations = new Dictionary<string, string>(); // 运行时翻译缓存 private Dictionary<string, string> _translations = new Dictionary<string, string>(); // 反向翻译查找 private Dictionary<string, string> _reverseTranslations = new Dictionary<string, string>(); // 正则表达式翻译规则 private List<RegexTranslation> _defaultRegexes = new List<RegexTranslation>(); // 分片翻译正则 private List<RegexTranslationSplitter> _splitterRegexes = new List<RegexTranslationSplitter>(); }翻译服务端点架构
插件化翻译服务接口
项目定义了统一的翻译服务接口,支持多种翻译服务的无缝集成:
public interface ITranslateEndpoint { string Id { get; } string FriendlyName { get; } int MaxConcurrency { get; } int MaxTranslationsPerRequest { get; } void Initialize(IInitializationContext context); IEnumerator Translate(ITranslationContext context); } // HTTP翻译端点基类 public abstract class HttpEndpoint : ITranslateEndpoint { protected abstract string ServiceUrl { get; } public IEnumerator Translate(ITranslationContext context) { var request = CreateHttpRequest(context); yield return SendRequest(request, response => { var translated = ParseResponse(response); context.Complete(translated); }); } }Google翻译端点实现
以Google翻译为例,展示了HTTP翻译服务的完整实现:
public class GoogleTranslateEndpoint : HttpEndpoint { private static readonly HashSet<string> SupportedLanguages = new HashSet<string> { "auto", "romaji", "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; public override string Id => "GoogleTranslate"; public override string FriendlyName => "Google! Translate"; public override int MaxTranslationsPerRequest => 10; }资源重定向系统设计
动态资源替换机制
XUnity.ResourceRedirector模块提供了强大的资源重定向能力,支持运行时资源替换:
public static class ResourceRedirection { // 资源加载Hook注册 public static void RegisterAssetLoadedHook( AssetLoadType loadType, Action<AssetLoadingContext> callback, int priority = 0) { var prioritized = new PrioritizedCallback<Action<AssetLoadingContext>>( callback, priority); switch (loadType) { case AssetLoadType.Asset: _prefixRedirectionsForAssets.Add(prioritized); break; case AssetLoadType.AssetBundle: _prefixRedirectionsForAssetBundles.Add(prioritized); break; } } // 异步资源加载支持 public static void RegisterAsyncAssetLoadedHook( AssetLoadType loadType, Action<AsyncAssetLoadingContext> callback, int priority = 0) { // 异步资源加载Hook实现 } }文本资源重定向实现
TextAsset资源重定向是翻译系统的核心组件:
public class TextAssetRedirector : IResourceRedirector { public bool CanHandle(AssetLoadingContext context) { return context.Parameters.Type == typeof(TextAsset); } public void Handle(AssetLoadingContext context) { var originalAsset = context.Asset as TextAsset; if (originalAsset != null) { // 加载本地化文本资源 var localizedText = LoadLocalizedText(context.Parameters.Path); if (localizedText != null) { var newAsset = ScriptableObject.CreateInstance<TextAsset>(); newAsset.text = localizedText; context.Complete(newAsset); } } } }多插件框架适配器设计
插件管理器兼容层
项目支持多种Unity插件框架,通过适配器模式实现统一接口:
// BepInEx插件适配器 public class AutoTranslatorPlugin : BaseUnityPlugin { private void Awake() { // 初始化核心翻译引擎 var translator = new AutoTranslationPlugin(); translator.Initialize(new BepInExEnvironment()); // 注册文本组件Hook RegisterTextHooks(); // 加载配置文件 LoadConfiguration(); } } // MelonLoader适配器 public class AutoTranslatorMelonModPlugin : MelonMod { public override void OnApplicationStart() { // MelonLoader特定初始化 var translator = new AutoTranslationPlugin(); translator.Initialize(new MelonModEnvironment()); } } // UnityInjector适配器 public class AutoTranslatorUnityInjectorPlugin : IPlugin { public void OnEnable() { // UnityInjector特定初始化 var translator = new AutoTranslationPlugin(); translator.Initialize(new UnityInjectorEnvironment()); } }高级翻译特性实现
正则表达式翻译引擎
项目实现了强大的正则表达式翻译系统,支持复杂文本匹配和替换:
public class RegexTranslation { public Regex Pattern { get; } public string Replacement { get; } public bool IsSplitter { get; } public bool TryTranslate(string input, out string output) { var match = Pattern.Match(input); if (match.Success) { output = Pattern.Replace(input, Replacement); return true; } output = null; return false; } } // 正则表达式翻译配置示例 public class RegexTranslationParser { public static RegexTranslation Parse(string line) { // 解析格式: r:"^Item ([0-9]+)$"="物品 $1" if (line.StartsWith("r:\"")) { var patternEnd = line.IndexOf('"', 3); var pattern = line.Substring(3, patternEnd - 3); var replacement = line.Substring(patternEnd + 2).Trim('"'); return new RegexTranslation( new Regex(pattern, RegexOptions.Compiled), replacement, false); } return null; } }翻译作用域管理
支持基于游戏场景和执行的翻译作用域控制:
public class TranslationScopeManager { private Dictionary<int, TranslationDictionaries> _scopedTranslations; public bool TryGetTranslation(string text, int scope, out string translation) { // 首先检查特定作用域的翻译 if (_scopedTranslations.TryGetValue(scope, out var dict)) { if (dict.TryGetValue(text, out translation)) return true; } // 回退到全局翻译 return _globalTranslations.TryGetValue(text, out translation); } // 作用域指令解析 public void ProcessDirective(string directive) { if (directive.StartsWith("#set level ")) { var levels = directive.Substring(11) .Split(',') .Select(int.Parse) .ToList(); _currentScopes.UnionWith(levels); } else if (directive.StartsWith("#unset level ")) { var levels = directive.Substring(13) .Split(',') .Select(int.Parse) .ToList(); _currentScopes.ExceptWith(levels); } } }性能优化策略
智能请求限流机制
为防止API滥用,项目实现了多层次的请求限流策略:
public class TranslationThrottler { private readonly Queue<DateTime> _requestTimestamps = new Queue<DateTime>(); private readonly int _maxRequestsPerMinute; private readonly TimeSpan _timeWindow = TimeSpan.FromMinutes(1); public bool CanMakeRequest() { var now = DateTime.UtcNow; var cutoff = now - _timeWindow; // 清理过期的时间戳 while (_requestTimestamps.Count > 0 && _requestTimestamps.Peek() < cutoff) { _requestTimestamps.Dequeue(); } // 检查是否超过限制 return _requestTimestamps.Count < _maxRequestsPerMinute; } public void RecordRequest() { _requestTimestamps.Enqueue(DateTime.UtcNow); } }内存缓存优化
采用LRU缓存策略优化翻译结果的内存使用:
public class TranslationCache : ITranslationCache { private readonly int _maxCacheSize; private readonly LinkedList<CacheEntry> _lruList; private readonly Dictionary<string, LinkedListNode<CacheEntry>> _cache; public bool TryGet(string key, out string value) { if (_cache.TryGetValue(key, out var node)) { // 移动到LRU列表前端 _lruList.Remove(node); _lruList.AddFirst(node); value = node.Value.Value; return true; } value = null; return false; } public void Add(string key, string value) { if (_cache.Count >= _maxCacheSize) { // 移除最久未使用的条目 var last = _lruList.Last; _cache.Remove(last.Value.Key); _lruList.RemoveLast(); } var node = new LinkedListNode<CacheEntry>( new CacheEntry { Key = key, Value = value }); _cache[key] = node; _lruList.AddFirst(node); } }配置管理系统
动态配置加载与验证
项目采用INI格式配置文件,支持运行时动态更新:
public class AutoTranslatorSettings { // 服务配置 public string ServiceEndpoint { get; set; } = "GoogleTranslate"; public string FallbackServiceEndpoint { get; set; } = ""; // 语言配置 public string Language { get; set; } = "en"; public string FromLanguage { get; set; } = "ja"; // 行为配置 public int MaxCharactersPerTranslation { get; set; } = 200; public bool EnableUIResizing { get; set; } = true; public bool EnableBatching { get; set; } = true; public bool UseStaticTranslations { get; set; } = true; // 文本框架支持 public bool EnableUGUI { get; set; } = true; public bool EnableTextMeshPro { get; set; } = true; public bool EnableNGUI { get; set; } = true; public bool EnableIMGUI { get; set; } = false; // 加载和保存配置 public static AutoTranslatorSettings Load(string path) { var settings = new AutoTranslatorSettings(); var ini = new IniFile(path); // 从INI文件加载配置 settings.ServiceEndpoint = ini.GetValue("Service", "Endpoint", "GoogleTranslate"); settings.Language = ini.GetValue("General", "Language", "en"); // ... 其他配置加载 return settings; } }扩展性与插件系统
自定义翻译端点开发
项目提供了完整的插件开发接口,支持第三方翻译服务集成:
// 自定义翻译端点示例 [Export(typeof(ITranslateEndpoint))] public class MyCustomTranslator : ITranslateEndpoint { public string Id => "MyCustomTranslator"; public string FriendlyName => "My Custom Translator"; public int MaxConcurrency => 1; public int MaxTranslationsPerRequest => 10; public void Initialize(IInitializationContext context) { // 初始化API密钥、端点URL等 var apiKey = context.GetOrCreateSetting("MyCustom", "ApiKey", ""); if (string.IsNullOrEmpty(apiKey)) throw new InvalidOperationException("API Key is required"); } public IEnumerator Translate(ITranslationContext context) { // 实现自定义翻译逻辑 var translations = context.UntranslatedTexts; var results = new string[translations.Length]; for (int i = 0; i < translations.Length; i++) { results[i] = await TranslateTextAsync(translations[i], context.SourceLanguage, context.DestinationLanguage); } context.Complete(results); yield break; } }资源重定向插件开发
支持自定义资源重定向器,实现特定游戏资源的本地化:
public class MyGameResourceRedirector : IResourceRedirector { public bool CanHandle(AssetLoadingContext context) { // 检查是否为特定游戏资源 return context.Parameters.Path.Contains("MyGame/SpecialAsset"); } public void Handle(AssetLoadingContext context) { // 实现资源替换逻辑 var localizedAsset = LoadLocalizedAsset(context); if (localizedAsset != null) { context.Complete(localizedAsset); } } } // 注册自定义重定向器 public class MyGamePlugin : BaseUnityPlugin { private void Awake() { ResourceRedirection.RegisterAssetLoadedHook( AssetLoadType.Asset, context => { var redirector = new MyGameResourceRedirector(); if (redirector.CanHandle(context)) { redirector.Handle(context); } }); } }测试与质量保证
单元测试框架
项目包含完整的单元测试套件,确保核心功能稳定性:
[TestClass] public class TranslationCacheTests { [TestMethod] public void TestCacheHit() { var cache = new TextTranslationCache(); cache.AddTranslation("Hello", "你好"); Assert.IsTrue(cache.TryGetTranslation("Hello", out var translation)); Assert.AreEqual("你好", translation); } [TestMethod] public void TestRegexTranslation() { var cache = new TextTranslationCache(); cache.AddRegexTranslation(@"^Item (\d+)$", "物品 $1"); Assert.IsTrue(cache.TryGetTranslation("Item 123", out var translation)); Assert.AreEqual("物品 123", translation); } } [TestClass] public class TranslatorEndpointTests { [TestMethod] public async Task TestGoogleTranslateEndpoint() { var endpoint = new GoogleTranslateEndpoint(); var context = new MockTranslationContext(); await endpoint.Translate(context); Assert.IsTrue(context.Completed); Assert.IsNull(context.Error); } }部署与集成指南
多框架支持矩阵
| 插件框架 | 支持版本 | IL2CPP支持 | 依赖管理 |
|---|---|---|---|
| BepInEx | 5.x, 6.x | 是 | 内置依赖 |
| MelonLoader | 0.3.x, 0.5.x, 0.6.x | 是 | 用户库管理 |
| IPA | 最新版 | 部分 | 插件目录 |
| UnityInjector | 兼容版本 | 否 | 独立部署 |
性能调优配置
[Service] Endpoint=GoogleTranslate MaxTranslationsPerMinute=60 MaxConcurrentTranslations=3 [Behaviour] EnableTranslationCaching=True CacheSizeLimit=1000 TranslationDelay=1000 EnableBatching=True MaxCharactersPerTranslation=200 [Performance] EnableAsyncLoading=True PreloadCommonTranslations=True CompressCacheFiles=True CacheValidationInterval=3600技术挑战与解决方案
Unity IL2CPP兼容性
项目通过反射和运行时Hook技术解决IL2CPP限制:
public class Il2CppCompatibilityLayer { // IL2CPP反射代理 public static object InvokeIl2CppMethod(object instance, string methodName, params object[] args) { if (IsIl2CppRuntime()) { // 使用IL2CPP专用调用机制 return Il2CppInterop.Invoke(instance, methodName, args); } else { // 使用标准.NET反射 return instance.GetType().GetMethod(methodName).Invoke(instance, args); } } // 文本组件Hook适配 public static void HookIl2CppTextComponent(Component component) { if (IsIl2CppRuntime()) { // IL2CPP特定的Hook实现 Il2CppTextHook.Hook(component); } else { // Mono运行时Hook实现 MonoTextHook.Hook(component); } } }内存管理与性能优化
采用对象池和延迟加载策略优化内存使用:
public class TranslationObjectPool { private readonly ConcurrentBag<TranslationContext> _pool; private readonly int _maxPoolSize; public TranslationContext Rent() { if (_pool.TryTake(out var context)) { context.Reset(); return context; } return new TranslationContext(); } public void Return(TranslationContext context) { if (_pool.Count < _maxPoolSize) { _pool.Add(context); } } } public class LazyTranslationLoader { private readonly Lazy<Dictionary<string, string>> _translations; public LazyTranslationLoader(string filePath) { _translations = new Lazy<Dictionary<string, string>>(() => { // 延迟加载翻译文件 return LoadTranslationsFromFile(filePath); }, LazyThreadSafetyMode.ExecutionAndPublication); } public string GetTranslation(string key) { if (_translations.Value.TryGetValue(key, out var translation)) return translation; return null; } }总结与展望
XUnity.AutoTranslator项目通过创新的架构设计和精心的工程实现,为Unity游戏本地化提供了完整的解决方案。其核心优势包括:
- 模块化设计:清晰的架构分层和职责分离
- 高性能实现:智能缓存、请求限流和内存优化
- 广泛兼容性:支持多种Unity版本和插件框架
- 可扩展性:插件化设计和开放的API接口
- 稳定性保障:完善的错误处理和恢复机制
未来发展方向包括AI翻译集成、离线翻译支持、实时协作翻译等功能的进一步增强,持续为游戏开发者提供更强大的本地化工具支持。
【免费下载链接】XUnity.AutoTranslator项目地址: https://gitcode.com/gh_mirrors/xu/XUnity.AutoTranslator
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考