SuperAPI AI Directory

cocos-i18n-skill

General & other

View repository

Updated 10-16 06:49

About this skill

Cocos Creator 3.8 Localization

Task Objectives

  • This Skill is used to: master Cocos Creator localization to implement multilingual support
  • Capabilities include: multilingual configuration, dynamic switching, localized resources
  • Trigger conditions: developing multilingual games, supporting internationalization and localization

Overview

Cocos Creator provides localization (i18n) support to help developers implement multilingual switching in games, enabling games to adapt to users in different regions and languages.

Localization Configuration

Install Plugin

  1. Open Cocos Creator
  2. Extensions -> Extension Store
  3. Search for the i18n plugin and install it

Configure Languages

import { i18n } from 'cc';

// 设置默认语言
i18n.init({
    locale: 'zh-CN'
});

// 切换语言
i18n.setLanguage('en-US');

Multilingual Files

JSON Format Configuration

{
    "zh-CN": {
        "game_title": "我的游戏",
        "start_btn": "开始游戏",
        "score": "得分:{score}"
    },
    "en-US": {
        "game_title": "My Game",
        "start_btn": "Start Game",
        "score": "Score: {score}"
    }
}

Load Language Packs

import { i18n } from 'cc';

i18n.loadScene('i18n/menu', (err, result) => {
    if (!err) {
        console.log('Language loaded');
    }
});

Use Localization

Get Text

// 获取本地化文本
const title = i18n.t('game_title');
const scoreText = i18n.t('score', { score: 100 });

Dynamically Update Label

import { Label } from 'cc';

const label = this.getComponent(Label);
i18n.updateLabel(label, 'game_title');

Automatic Component Update

import { I18n } from 'cc';

const i18nComponent = this.node.addComponent(I18n);
i18nComponent.dataID = 'game_title';

Language Switching

Listen for Language Changes

i18n.on('language-changed', () => {
    console.log('Language changed to:', i18n.currentLanguage);
    // 刷新界面文本
    this.refreshUI();
});

Persist Language Settings

import { sys } from 'cc';

// 保存语言设置
sys.localStorage.setItem('language', i18n.currentLanguage);

// 加载语言设置
const savedLang = sys.localStorage.getItem('language');
if (savedLang) {
    i18n.setLanguage(savedLang);
}

Formatting

Parameter Substitution

// {0}, {1} 占位符
i18n.t('items_count', { 0: items.length });

// 命名参数
i18n.t('player_level', { level: player.lv, name: player.name });

Plural Forms

i18n.t('apple_count', { count: appleNum });
// zh-CN: 1个苹果 / 2个苹果
// en-US: 1 apple / 2 apples

Resource Index

Necessary References

Notes

Performance Optimization

  • Avoid frequent language switching
  • Cache loaded language packs
  • Lazy-load resources for non-current languages

Best Practices

  • Use key-value pairs instead of hardcoded text
  • Ensure proper text length adaptation
  • Pay attention to RTL (right-to-left) language support