Communitygithub.com

unity-technologies/localization

设置并配置 Unity Localization,包括语言环境、字符串/资源表、CJK 字体支持以及 Addressables 工作流。当用户想要为项目添加语言、翻译 UI 文本、通过 TMP 字体支持亚洲(CJK)语言,或提到 i18n、l10n、多语言支持或让游戏支持多种语言时使用。

localization 是什么?

此技能提供了一套全面的 Unity Localization 设置与配置指南,涵盖从基础的语言环境(Locale)和字符串/资源表(String/Asset Tables)到 Addressables 集成以及亚洲语言(CJK)字体支持等高级功能。其核心价值在于通过清晰的步骤和模式,帮助开发者避免常见陷阱,例如因包未正确安装而导致的静默失败、通过错误方式切换语言环境、以及使用不可靠的 TMP 回退字体来处理 CJK 字符。技能文档提供了详尽的“安全填充模式”(Safe Population Pattern)来操作表格数据,并强调了在 Unity 编辑器中正确刷新和通知的重要性。此外,它还明确了编辑器中预览语言环境和运行时切换语言环境的正确方法,并强烈反对手写语言状态管理,以保持整个项目的同步性。对于亚洲语言支持,它推荐使用可靠的“资源表字体切换”(Asset Table Font Swapping)方案,并指出了导入 TMP Essential Resources 的先决条件。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/unity-technologies/skills/tree/main/skills/localization

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

本指南涵盖设置和配置 Unity Localization,包括语言环境、字符串和资源表、Addressables 集成以及通过资源表实现的 CJK 字体支持。

0. 包安装检查

在执行其他操作之前,请先验证 Localization 包是否已安装。如果该包不存在,此技能中的许多 API 将会静默失败或抛出令人困惑的错误。

  1. 通过读取项目文件检查,而不是询问 Package Manager。 在 Packages/packages-lock.json 中查找 com.unity.localization。该文件记录了 Unity 实际解析的内容,是纯 JSON 格式,读取它无需编辑器也无需异步调用。(Packages/manifest.json 仅记录请求的内容,所以请检查锁文件。)
  2. 如果缺失则安装: UnityEditor.PackageManager.Client.Add("com.unity.localization")。
  3. 正确等待。 Client.Add 和 Client.List 是异步的:它们返回一个在调用返回时仍处于 InProgress 状态的请求,因此在同一语句中读取结果没有任何意义。也不要忙等 IsCompleted;这会阻塞您正在运行的主线程。相反,在触发安装后返回,然后在后续调用中轮询 packages-lock.json,直到 ID 出现。安装还会触发域重载,因此预计前一到两次轮询可能会失败;新安装通常会在几秒钟内完成解析。
  4. 在使用前确认类型已实际加载,因为锁文件可能在程序集准备就绪之前就被写入:
    var t = System.Type.GetType(
        "UnityEngine.Localization.Settings.LocalizationSettings, Unity.Localization");
    return t != null ? "ready" : "not loaded yet";
    
    仅在返回 ready 后才继续操作。

1. Localization 设置与语言环境

如果 LocalizationEditorSettings.ActiveLocalizationSettings 为 null,则必须找到或创建它:

  1. 查找: 使用 AssetDatabase.FindAssets("t:LocalizationSettings", new[] { "Assets" })。如果找到,加载第一个并将其分配给 LocalizationEditorSettings.ActiveLocalizationSettings。
    • 始终传递搜索文件夹。 无范围限定的 FindAssets 会搜索整个项目,包括只读包,因此它可能会返回包中的资源,导致项目指向您无法编辑的内容。这适用于此技能中的每个 FindAssets 调用。
  2. 创建: 如果未找到,创建一个新实例并将其保存到 Assets/Localization/LocalizationSettings.asset。使用 ScriptableObject.CreateInstance<LocalizationSettings>(),然后使用 AssetDatabase.CreateAsset()。
  3. 激活: 设置 LocalizationEditorSettings.ActiveLocalizationSettings = settings。
  4. 语言环境: 确保语言环境(en、fr、de 等)存在。如果缺失则创建,并使用 LocalizationEditorSettings.AddLocale(locale) 将其添加到设置中。

2. 修改 Localization 表

对字符串或资源表的程序化更改需要通知编辑器。始终创建所需的资源表,除非项目中已存在现有表。

安全填充模式

从数据集填充表时,显式地通过 Locale.Identifier.Code 进行匹配。GetLocales() 的顺序不能保证与您的输入数据数组匹配——假设它会匹配将导致难以调试的静默数据不匹配。 对于资源表,使用资源的 GUID:table.GetEntry(sharedId) ?? table.AddEntry(sharedId, guid);。

刷新与通知

进行任何修改(添加键、更新值)后,通知编辑器以便其刷新内部状态。跳过此步骤将使编辑器显示过时数据,直到下次重新导入。

  1. 在每个修改过的 Table 上调用 EditorUtility.SetDirty(collection)、EditorUtility.SetDirty(collection.SharedData)。
  2. Unity 6+ 通知: LocalizationEditorSettings.EditorEvents.RaiseCollectionModified(sender, collection);
  3. 最后始终调用 AssetDatabase.SaveAssets()。

3. UI 本地化与布局

命名空间与冲突

  • 始终使用完全限定名称: 使用 UnityEngine.UI.Image、UnityEngine.UI.VerticalLayoutGroup、UnityEngine.UI.ScrollRect、UnityEngine.UI.Mask、UnityEngine.UI.CanvasScaler、UnityEngine.UI.GraphicRaycaster、UnityEngine.UI.ContentSizeFitter、UnityEngine.UI.LayoutRebuilder 等。
  • UnityEngine.UI 既是一个命名空间也是一个类容器,因此非限定名称会导致 CS0118(将命名空间用作类型)错误。完全限定可以完全避免这一点。
  • 单实例: 在创建新画布之前,始终检查 GameObject.Find("YourCanvasName") 并销毁旧画布。
  • 语言环境切换:使用包,并将预览和运行时分开。 这是两种不同的机制,将它们混为一谈正是导致语言环境切换最终经常手写的症结所在。
    • 在编辑时预览语言环境,请使用 Localization Scene Controls 窗口 (Window > Asset Management > Localization Scene Controls)。这仅限于编辑器。它不是运行时功能,因此当游戏本身需要语言设置时,它并不是答案。
    • 在运行时切换语言环境,请分配 LocalizationSettings.SelectedLocale。这是受支持的入口点,通过 LocalizeStringEvent 绑定的所有内容都会随之更新。
    • 要固定游戏启动时的语言环境,请在 Localization Settings 资源上配置启动语言环境选择器。SpecificLocaleSelector 是强制使用所选语言环境的选择器;否则,默认链会选择系统语言。
    • 永远不要手写语言环境状态。 在游戏中实现一个真正的语言菜单是可以的,也是预期的,只要它设置 SelectedLocale 并让包传播更改。禁止的做法是:一个调试下拉菜单或菜单维护自己的“当前语言”变量,自己交换字符串,或绕开包进行操作,因为项目中的其他任何东西都不会跟随它。

本地化字符串事件(稳健绑定)

  • 检查组件类型: 确定目标是 TextMeshPro 还是传统的 UnityEngine.UI.Text。

  • 正确绑定: 添加公开的 UnityEngine.Localization.Components.LocalizeStringEvent 组件并自行连接——将 StringReference 设置为表条目,然后添加一个 OnUpdateString 监听器,将值分配给文本组件(TextMeshPro 使用 TMP_Text.text,传统 Text 使用 UnityEngine.UI.Text.text)。

    不要反射到 UnityEditor.Localization.Plugins.TMPro.LocalizeComponent_TMPro 或其 UGUI 对应类中。这些是 internal 的(在 Localization 1.5.12 上测量),因此访问它们意味着绕过访问控制,使用一个 Unity 未做稳定性承诺的 API——它可以在任何包版本中更改或消失。LocalizeStringEvent 是公开的,并且通过显式的接线完成相同的工作。

  • 布局重建: 设置本地化文本或填充列表后,调用 UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(parentTransform) 以确保尺寸更新。

4. 亚洲语言字体支持(CJK)

避免为 CJK 语言环境使用 TMP 后备字体。应改为对每个特定语言环境使用资源表字体切换——在字形缺失时,后备字体不可靠且难以调试。

先决条件:必须导入 TMP Essential Resources

在接触任何 TMP API 之前进行此项检查。 在从未导入过这些资源的项目中,TMP_Settings.instance 为 null,并且 TMP 调用会因一个不提供有用信息的简单 NullReferenceException 而失败。TMP_FontAsset.CreateFontAsset 就是其中之一,因此字体创建会在第一行就因错误而终止。

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

unity-technologies/2d-pixel-perfect

Sets up, diagnoses, and fixes pixel perfect 2D rendering in Unity projects. Use when working on any retro-style or pixel art 2D game.

unity-technologies/audio-setup-mixers

Scans the scene and audio assets to appropriately route Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. Creating mixers and groups, and setting volumes, are not automated — the skill inventories what exists and asks the user to add anything missing.

unity-technologies/build-live-game

Build and operate a live game using Unity Services. Use when the user needs to implement, connect, or debug backend-driven features — battle passes, achievements, player progression, cloud saves, leaderboards, matchmaking, virtual economies, server-authoritative logic, anti-cheat, player accounts and authentication, remote configuration, feature flags, A/B testing, analytics, or cloud resource deployment. Triggers on live-ops, live service, backend, server authority, cloud code, cloud save, remote config, player data, retention, monetization loop, season pass, ranking, multiplayer sessions, lobbies, or any Unity Services integration.

unity-technologies/generate-editor-search-query

Generates Unity Search / Quick Search queries and opens the Unity Search window for read-only Unity Editor asset or scene-object lookup requests. Always use when the user asks to find, search, show, locate, filter, look up, query, or list concrete assets or scene objects in the current project or scene, even if Unity Search is not named. Covers materials, textures, prefabs, scenes, scripts, shaders, GameObjects, components, Lights, Cameras, UI objects, labels, paths, references, selected or named assets, and asset types. Also use when the user explicitly mentions Unity Search, Quick Search, Search window, open Search, or asks what Unity Search query to use. Do not use for general project overview, project structure, folder-purpose summaries, gameplay/system explanations, how-to programming questions, web search, repository text search, build logs, package installation, menu or settings search, modifying results, or non-Unity filesystem search unless the user explicitly asks to use Unity Search.

unity-technologies/implement-in-app-purchases

Implement, configure, and debug Unity In-App Purchases (IAP) — store connection, product catalog, consumable/non-consumable/subscription purchases, two-step pending-confirm flow, receipt validation, entitlement checking, restore transactions, Apple extensions (promotional purchases, Ask-to-Buy, code redemption), and Google Play extensions (subscription upgrade/downgrade), D2C Capabilities(direct to customer), 3rd party payment provider (Stripe/Coda) via Unity IAP/Unity Cloud. Use when the user needs to add, modify, debug, or migrate from native Android/iOS billing, 3rd party packages(RevenueCat/Adapty/Essential Kit/Unipay supported) to IAP. Triggers on microtransactions (MTX), monetization, real-money purchases, store purchases, buying items, support D2C, purchase via Stripe/Coda, migrate from native billing(Google's BillingClient or Apple's StoreKit/SKPaymentQueue/SKProduct)/RevenueCat/Adapty/EssentialKit/Unipay.

unity-technologies/initialize-ai-navigation

Sets up and configures the Unity AI Navigation system — NavMesh surfaces, NavMesh agents, obstacles, links, modifiers, areas and costs. Use when creating walkable navigation meshes, adding pathfinding agents, setting up patrol routes, configuring obstacle avoidance and carving, connecting separate NavMeshes with links, coupling navigation with animation, or troubleshooting navigation issues.

unity-technologies/levelplay-unity-integration

Integrates the LevelPlay Mediation SDK via the Ads Mediation UPM package. Use when a developer asks about adding ads to a Unity game, implementing rewarded, interstitial, or banner ads, setting up ad mediation, configuring ad networks, installing or updating the Ads Mediation package, troubleshooting LevelPlay namespace errors, resolving Android gradle or iOS CocoaPods dependency issues for ads, configuring ATT or privacy settings for ad compliance, tracking impression-level revenue (ILRD), initializing the LevelPlay SDK, or setting up ad unit IDs. Also use when a developer wants to monetize their Unity game with ads, asks how to get started with LevelPlay, ads, or mediation, or needs help with any part of the LevelPlay integration workflow including platform-specific setup for iOS or Android. Also use when upgrading the LevelPlay or IronSource SDK version, migrating from deprecated IronSource.Agent APIs, or migrating a game from Unity Ads to LevelPlay.

unity-technologies/manage-sprite-atlas

Manage SpriteAtlas using prebuild pipeline with IPreprocessBuildWithReport (DEFAULT approach). Use it to configure master atlases, variant atlases, texture settings, packing settings, and platform-specific configurations. Use when the user asks about creating sprite atlases, optimizing sprites, configuring atlas settings, adding sprites to atlases, creating variant atlases, implementing automated atlas generation, or runtime sprite atlas access. Always use prebuild approach unless user explicitly requests manual authoring.

unity-technologies/migrate-birp-to-urp

Plans, executes, and troubleshoots Unity projects moving from the Built-in Render Pipeline (BiRP/BIRP/Built-in RP) to the Universal Render Pipeline (URP). Use when the user asks to upgrade, convert, switch, or migrate a project, scene, material, or shader to URP/Universal Render Pipeline; fix pink or magenta materials after URP; convert Built-in materials/shaders; move a 2D project to URP 2D; review lighting, quality, post-processing, baked lightmaps, or reflection probes after URP; or diagnose visual problems after a render-pipeline migration.

相关技能