Communitygithub.com

unity-technologies/localization

設定和配置 Unity Localization,包含語言環境、字串/資源表、CJK 字體支援以及 Addressables 工作流程。當使用者想要為專案新增語言、翻譯 UI 文字、支援亞洲(CJK)語言的 TMP 字型,或提及 i18n、l10n、多語言支援、讓遊戲支援多種語言時使用。

localization 是什麼?

本技術指南詳細說明如何在 Unity 專案中設定 Localization 套件,涵蓋從安裝檢查到亞洲語系字型支援的完整流程。其核心價值在於提供一套經過實戰驗證的可靠模式,避免開發者踩中常見的陷阱,例如套件非同步安裝的等待方式、不安全的資料表編輯操作,以及割裂的語言切換實作。指南明確區分了編輯器預覽(Localization Scene Controls)與執行時切換(LocalizationSettings.SelectedLocale)兩種機制,並強烈禁止繞過套件自行管理語言狀態。對於文字元件綁定,它推薦使用公開的 LocalizeStringEvent 元件,而非依賴內部 API,以確保穩定性。此外,針對 CJK 字型,它提供了透過 Asset Table 進行字型交換的可靠方案,作為 TMP Fallback Fonts 的替代。此指南主要適用於 Unity Editor 中的開發工作,並假設開發者會透過 C# 腳本進行程式化操作,而非依賴編輯器視窗的點擊。

相容平台~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 格式,讀取它不需要 Editor 也不需要非同步呼叫。(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 Settings 與 Locales

如果 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. 修改本地化資料表

對字串或資源表進行程式化修改需要通知 Editor。 除非專案中已有現有的資料表,否則始終建立所需的資源表。

安全填充模式

從資料集填充資料表時,請明確地透過 Locale.Identifier.Code 進行比對。GetLocales() 的順序無法保證與您的輸入資料陣列相符 — 假設它們相符將導致難以除錯的靜默資料不匹配。 對於資源表,請使用資源的 GUID:table.GetEntry(sharedId) ?? table.AddEntry(sharedId, guid);。

重新整理與通知

在進行任何修改(新增金鑰、更新值)之後,通知 Editor 以便它重新整理其內部狀態。跳過此步驟將使 Editor 顯示過時的資料,直到下次重新匯入為止。

  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)。這僅限 Editor。它不是一個執行時功能,因此當遊戲本身需要語言設定時,這不是答案。
    • 要在執行時切換語言環境,請指派 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 Fallback Fonts。請改為為每個特定語言環境使用資源表字型交換 — 回退字型不可靠,且在字型缺失時難以除錯。

先決條件:必須匯入 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.

相關技能