creator-编辑器扩展

creator-编辑器扩展


前篇


创建

  1. 扩展 -> 创建扩展

    image-20230323172156057

  2. 选择模板, 指定扩展名, 如 its-util, 就会在, extensions 中创建一个 its-util 扩展目录

    image-20230323172310283

  3. 然后执行初始化命令

    1
    2
    $ cd its-util
    $ npm install && npm run build
  4. 启用扩展

    image-20230323172538532


修改扩展

  1. 改为代码, build 一下才生效, 然后, 这种方式不如 npm run watch 方便, 开启监听后不用再去 build 了

    1
    $ npm run build
  2. 点击 刷新 按钮

    image-20230323174637625


开发模式

  1. 打开监听, 就不用每次都 build 了

    1
    $ npm run watch
  2. 点击 刷新 按钮

    image-20230324110637993

    • 貌似代码卸载 main.ts 和 vue 模板 ts 内的才能刷新生效, 写在 main.ts 里已用其他 ts 里面的代码则不生效

      image-20230324113348477

  3. done


消息机制

大部分常用的编辑器扩展 api 需要通过消息来进行通讯


引擎消息 api

  • 开发者 -> 消息列表 中可以查看相关的 api

    image-20230325143642949

  • 以查询 url 路径为例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
        let uuid = "a7ac6d76-4a06-46ad-8d58-363b1b46ad6c"
    const info = await Editor.Message.request('asset-db', 'query-url', uuid);
    LogUtil.D('--- info:', info) // db://assets/resources/ui/Atlas/login/bx_loading_Phone.png



    ---

    #### 扩展消息 api

    - https://docs.cocos.com/creator/manual/zh/editor/extension/messages.html#%E6%99%AE%E9%80%9A%E6%B6%88%E6%81%AF

    1. 定义消息. 在 *package.json* 中定义消息

    ```json
    {
    "name": "its-util", // name 就是要调用的 扩展包名
    "contributions": {
    "messages": {
    "test-api01": { // test-api01 就是要执行的消息
    "methods": [ // methods 就是该消息会执行的方法数组, 一般定义一个就行了
    "api001"
    ]
    },
    "test-api02": {
    "methods": [
    "api002"
    ]
    },
    }
    }
    }
  1. main.ts 中定义具体的方法

    ```typescript
    // @ts-ignore
    export const methods: { [key: string]: (…any: any) => any } = {

     api001(...args: any[]) { // 不需要返回值, 提供给 send
         LogUtil.D("--- api001 args:", ...args)
     },
    
     api002(...args: any[]) { // 需要返回值, 且支持异步返回, 提供给 request
         LogUtil.D("--- api002 args:", ...args)
         return new Promise<string>((resolve) => {
             setTimeout(() => {
                 resolve("--- msg from api002")
             }, 3000);
         })
     },
    

    };

  2. 测试

    ```json
    // 发送
    Editor.Message.send(“its-util”, “test-api01”, “hello”, 123, true);

    // 请求并返回
    const info02 = await Editor.Message.request(“its-util”, “test-api02”, “hello”, 123, true);


资源管理器扩展

可以在资源里面右键增加扩展, 方便对资源做处理


自定义构建流程


vue3


生命周期

  • a

    image-20230325111508551


踩坑

自定义扩展修改不生效

  • 如果修改了代码, 也执行了 npm run build 还是不生效, 重启工程

构建扩展不生效

  • 构建工具修改后, 需要刷新构建进程, 才能是代码生效

    打开构建调试工具, ctrl + R 刷新即可

    image-20230420164201763