[分享] Cocos Creator 项目&插件开发常用API列表(2.x/3.x)

[分享] Cocos Creator 项目&插件开发常用API列表(2.x/3.x)

推荐编码规范 | Cocos Creator

示例插件 Cocos 2x & Cocos 3x 兼容 ↓ 👇

:point_up_2:https://store.cocos.com/app/detail/3740

编辑器扩展基础

插件入口声明

// package.json
{
  "name": "your-plugin-name",
  "version": "1.0.0",
  "main": "./main.js",
  "editor": ">=2.4.0 || >=3.0.0",
  "panels": {
    "default": {
      "title": "Panel Title",
      "main": "./panel/index.js",
      "type": "dockable",
      "width": 400,
      "height": 300
    }
  }
}

资源管理器API体系

1. 核心文件操作


// 查询文件元信息

Editor.assetdb.queryInfoByUuid(uuid, (err, info) => {

  console.log('文件路径:', info.path, '资源类型:', info.type);

});

// 移动/重命名文件

Editor.assetdb.move('db://assets/oldPath.txt', 'db://assets/newPath.txt');

// 创建或覆盖文件

Editor.assetdb.createOrSave('db://assets/script.js', '// New script content');

// 批量删除资源

Editor.assetdb.delete([

  'db://assets/temp1.png',

  'db://assets/temp2.png'

]);

// 强制刷新资源管理器

Editor.assetdb.refresh('db://assets/');

2. 路径转换服务


// UUID转URL路径

const assetUrl = Editor.remote.assetdb.uuidToUrl(fileUUID);

// 绝对路径转项目路径

const projectPath = Editor.remote.assetdb.fspathToUrl('/User/project/assets/image.png');

// URL转UUID标识

const assetUUID = Editor.remote.assetdb.urlToUuid('db://assets/image.png');

3. 选择状态管理


// 清空资源选择

Editor.Selection.clear('asset');

// 设置选中指定资源

Editor.Selection.select('asset', '5f7a1b-xxxx-xxxx');

// 获取当前选中资源列表

const selectedAssets = Editor.Selection.curSelection('asset');

// 检测当前焦点面板类型

const activePanel = Editor.Selection.curGlobalActivate();

if (activePanel.type === 'asset') {

  // 资源管理器处于焦点状态

}

场景编辑器深度集成

1. 节点操作指令


// 创建空白节点(参数:节点名称,父节点UUID)

Editor.Ipc.sendToPanel('scene', 'scene:create-node-by-classid', 'NewNode', '', parentUUID);

// 动态添加组件(参数:节点UUID,组件类型)

Editor.Ipc.sendToPanel('scene', 'scene:add-component', nodeUUID, 'cc.Sprite');

// 批量删除节点(参数:节点UUID数组)

Editor.Ipc.sendToPanel('scene', 'scene:delete-nodes', [nodeUUID1, nodeUUID2]);

// 实例化预制件(参数:预制件UUID,父节点UUID)

Editor.Ipc.sendToPanel('scene', 'scene:create-nodes-by-uuids', [prefabUUID], parentUUID);

2. 属性动态修改


// 修改节点名称

Editor.Ipc.sendToPanel('scene', 'scene:set-property', {

  id: nodeUUID,

  path: 'name',

  type: 'String',

  value: 'NewName',

  isSubProp: false

});

// 更新Sprite组件纹理

Editor.Ipc.sendToPanel('scene', 'scene:set-property', {

  id: spriteCompUUID,

  path: 'spriteFrame',

  type: 'cc.SpriteFrame',

  value: { uuid: textureUUID },

  isSubProp: false

});

3. 预制件管理系统


// 创建预制件(参数:节点UUID,保存路径)

Editor.Ipc.sendToPanel('scene', 'scene:create-prefab', nodeUUID, 'db://assets/prefab/new.prefab');

// 应用预制件修改

Editor.Ipc.sendToPanel('scene', 'scene:apply-prefab', prefabInstanceUUID);

// 解除预制件关联

Editor.Ipc.sendToPanel('scene', 'scene:break-prefab-instance', prefabInstanceUUID);

事件通讯体系

1. 资源事件监听


// 监听资源创建事件

Editor.Ipc.addListener('asset-db:assets-created', (event, uuids) => {

  uuids.forEach(uuid => {

    console.log('新资源创建:', uuid);

  });

});

// 监听资源删除事件

Editor.Ipc.addListener('asset-db:assets-deleted', (event, uuids) => {

  // 处理资源删除逻辑

});

2. 场景事件响应


// 场景加载完成事件

Editor.Ipc.addListener('scene:ready', () => {

  console.log('场景编辑器初始化完成');

});

// 节点组件添加事件

Editor.Ipc.addListener('scene:node-component-added', (event, nodeUUID, compName) => {

  console.log(`节点 ${nodeUUID} 添加了 ${compName} 组件`);

});

3. 主动事件触发


// 高亮指定资源

Editor.Ipc.sendToAll('assets:hint', targetUUID);

// 打开外部编辑器(参数:资源UUID)

Editor.Ipc.sendToMain('assets:open-text-file', scriptUUID);

// 触发资源搜索

Editor.Ipc.sendToAll('assets:search', 'texture');

调试与监控技巧

1. IPC通讯监控


// 记录所有面板通讯

const originalSend = Editor.Ipc.sendToPanel;

Editor.Ipc.sendToPanel = (panelName, message, ...args) => {

  console.group('IPC Message');

  console.log('Target Panel:', panelName);

  console.log('Message Type:', message);

  console.log('Parameters:', args);

  console.groupEnd();

  return originalSend(panelName, message, ...args);

};

2. 面板直接操作


// 切换场景编辑器工具模式

document.getElementById('tools').transformTool = 'rotate';

// 获取预览服务器地址

const previewURL = document.getElementById('playButtons').dataHost.previewURL;

// 强制刷新属性面板

document.getElementById('inspector')._clear();

重要事件列表

事件分类 关键事件名称 触发时机
资源管理 asset-db:assets-created 新资源创建完成时
asset-db:assets-moved 资源移动/重命名操作后
asset-db:asset-changed 资源内容发生修改时
场景操作 scene:ready 场景编辑器初始化完成
scene:node-component-added 节点添加新组件时
scene:set-property 节点属性被修改时
用户交互 selection:activated 面板获得焦点时
assets:popup-context-menu 资源管理器弹出右键菜单时

安全与最佳实践

  1. 操作验证:关键文件操作前应检查路径有效性

if (!Editor.assetdb.exists('db://assets/config.json')) {

  Editor.warn('配置文件不存在!');

  return;

}

  1. 批处理优化:批量操作使用队列控制

const taskQueue = new TaskQueue();

fileList.forEach(file => {

  taskQueue.push(done => {

    Editor.assetdb.move(file.oldPath, file.newPath, done);

  });

});

  1. 内存管理:及时清理事件监听

// 插件卸载时

onUnload() {

  Editor.Ipc.removeAllListeners('asset-db:assets-created');

}

  1. 错误处理:完善回调错误捕捉

Editor.assetdb.delete(paths, err => {

  if (err) {

    Editor.error('删除失败:', err.stack);

    showErrorMessage(err.message);

  }

});

注意事项

  1. 版本差异:3.x使用更模块化的API结构,建议优先使用ES6模块语法

  2. 路径处理:使用Path模块处理跨平台路径问题

  3. 权限问题:文件操作需在asset-db作用域内执行

  4. 类型检查:3.x推荐使用TypeScript开发,可获得更好的类型提示

  5. 生命周期:注意不同版本的面板生命周期差异

实际使用时请根据具体版本文档调整参数,本列表基于Cocos Creator 2.4.10和3.6.1版本整理

1赞

实际处理还有待验证完善的地方,上文阐述自 deepseek 整理,校验中,不足之处还请各位大佬补充

可参考的一些资料:

后续内容会慢慢补充

mark!!!