### Full Guide Flow Example Source: https://mkframework.muzzik.cc/docs/module/guide/manage Demonstrates the complete lifecycle of setting up, registering steps, listening to events, and starting/ending a guide. ```javascript // 1. 创建管理器 const guide = new mk.GuideManage({ nameStr: '测试引导', endStepNum: 999, operateTab: { tip: { load: () => showTip(), unload: () => hideTip(), }, }, }); // 2. 注册步骤 guide.regis([new FirstStep(1), new SecondStep(2)]); // 3. 监听事件 guide.event.on(guide.event.key.finish, () => { console.log('✅ 引导完成'); }); // 4. 开始引导 guide.setStep(1); // 5. 结束引导,跳转到 endStepNum 步骤或调用 finish 函数 guide.setStep(999); // guide.finish(); ``` -------------------------------- ### Create Guide Manager Instance Source: https://mkframework.muzzik.cc/docs/module/guide/manage Instantiate mk.GuideManage with initial configuration. The `stepUpdateCallbackFunc` can be used to interrupt the guide by returning null or undefined. ```javascript const guideManager = new mk.GuideManage({ currentStepNum: 1, // 初始步骤编号 endStepNum: 10, // 结束步骤编号 nameStr: '新手引导', // 引导名称(用于日志) operateTab: XXXGuideOperate.tab, // 操作单元表 stepUpdateCallbackFunc: (stepNum) => { /* 步骤更新回调 */ }, }); ``` -------------------------------- ### Listen to Guide Events Source: https://mkframework.muzzik.cc/docs/module/guide/manage Utilize the `event` property to subscribe to various guide lifecycle events. Use `guideManager.event.key.xxx` to avoid typos. ```javascript guideManager.event.on(guideManager.event.key.loadingStep, () => { // 步骤加载开始 }); ``` -------------------------------- ### Register Guide Steps Source: https://mkframework.muzzik.cc/docs/module/guide/manage Register one or more step instances with the guide manager. The `guideManage` property of the step instance will be automatically set. ```javascript regis(step_: MKGuideStepBase | MKGuideStepBase[]): void ``` -------------------------------- ### Log Output for JSON Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Example log output demonstrating the reception and request-response cycle for messages with IDs and sequences. ```text 监听返回 {id: 0, sequence: 0, data: 123} 监听返回 {id: 0, sequence: 1, data: 456} 请求返回 {id: 0, sequence: 1, data: 456} ``` -------------------------------- ### Complete MVC Module Example (Shop) Source: https://mkframework.muzzik.cc/docs/module/module/mvc A full example demonstrating a Shop module with its Control, Model, and View. The Control handles interactions like buying items and closing the shop. ```typescript class ShopControl extends mk.MVCControlBase { protected async open() { this._model = await ShopModel.new(); this._view = (await ShopView.new())!; this._view.event.once('buy', (itemId) => { this._model.gold -= 100; // 扣钱 console.log(`购买物品 ${itemId}`); }); this._view.event.once('close', () => this.close()); } } class ShopModel extends mk.MVCModelBase { gold = 1000; } class ShopView extends mk.MVCViewBase { static async new() { mk.uiManage.regis(ShopView, 'db://assets/Shop.prefab', null); return mk.uiManage.open(ShopView); } } ``` ```typescript const shop = new ShopControl(); // 自动执行 open() ``` -------------------------------- ### Finish Guide Source: https://mkframework.muzzik.cc/docs/module/guide/manage Manually complete the guide. This sets `isPause` and `isFinish` to true and triggers the `finish` event. It can be used for forced termination. ```javascript finish(): void ``` -------------------------------- ### Pause and Resume Guide Source: https://mkframework.muzzik.cc/docs/module/guide/manage Control the guide's pause state using the `isPause` property. Setting `isPause` to true pauses the guide, triggering a `pause` event, while setting it to false resumes it, triggering a `resume` event. ```javascript guideManager.isPause = true; // 暂停,触发 pause 事件 ``` ```javascript guideManager.isPause = false; // 恢复,触发 resume 事件 ``` -------------------------------- ### Simple Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Demonstrates the basic usage of creating a WebSocket instance, connecting to a server, sending string messages, and listening for all received messages. ```APIDOC ## Simple WebSocket Usage ### Description This example shows how to create a generic WebSocket object, connect to a server, send string messages, and listen for all incoming messages. ### Steps 1. **Create Websocket Instance**: `const ws = new mk.network.Websocket();` 2. **Connect to Server**: `await ws.connect('ws://127.0.0.1:8848');` 3. **Send String Message**: `ws.message.send('123');` 4. **Listen for All Messages**: `ws.event.on(ws.event.key.recv, (data: string) => { console.log('Received message', data); }, this);` ``` -------------------------------- ### Get Current Step Source: https://mkframework.muzzik.cc/docs/module/guide/manage Retrieve the current step number from the guide manager. ```javascript getStep(): number ``` -------------------------------- ### Get Module Instances Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves currently open module instances. ```APIDOC ## get `get()` / `get(key)` / `get(key, type)` ### Parameters * No parameters: Retrieves all currently open modules. * `key`: * `Constructor`: Returns the last opened module instance. * `[Constructor]`: Returns a list of all opened module instances. * `type`: Filters the results; matches modules where `module.typeStr === type`. ### Example ``` // Get all currently open ViewBase objects const all = mk.uiManage.get(); // Get the last opened Test module const test = mk.uiManage.get(Test); // Get a list of all opened Test modules const testList = mk.uiManage.get([Test]); // Get the last opened Test module with type 'default' const panelOfTypeA = mk.uiManage.get(Test, 'default'); // Get a list of all opened Test modules with type 'default' const panelOfTypeAList = mk.uiManage.get([Test], 'default'); ``` ``` -------------------------------- ### Simple Websocket Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Connect to a WebSocket server and send/receive string messages. Listen for all incoming messages using the 'recv' event key. ```typescript const ws = new mk.network.Websocket(); // 连接服务器 await ws.connect('ws://127.0.0.1:8848'); // 发送字符串消息 ws.message.send('123'); // 监听所有返回的消息 ws.event.on( ws.event.key.recv, (data: string) => { console.log('收到消息', data); }, this ); ``` -------------------------------- ### Set Guide Step Source: https://mkframework.muzzik.cc/docs/module/guide/manage Update the current step and automatically execute `run()` if not paused. Handles normal, paused, and completed states, triggering events before switching. ```javascript setStep(stepNum_: number, initData_?: any): Promise ``` -------------------------------- ### Get Directory Resources Source: https://mkframework.muzzik.cc/docs/module/asset/asset Use the getDir interface to load resources from a folder. Supports local and remote environments. Parameters are similar to the get interface. ```javascript getDir(pathStr_, type_, target_, config_?) ``` -------------------------------- ### mk.Storage Properties and Methods Source: https://mkframework.muzzik.cc/docs/module/data/storage Details on accessing storage keys and performing operations like get, set, delete, and clear. ```APIDOC ### Properties #### key Access all storage keys. Useful for editor auto-completion and consistent key management. *Example:* ```javascript storage.key ``` * * * ### Methods #### get Retrieves data from storage. Returns the default value from the constructor's `data` if the key does not exist, otherwise returns `null`. *Example:* ```javascript storage.get(storage.key.testStr) ``` * * * #### set Stores data locally in JSON format. If `nameStr` is not set, data is temporarily cached. Once `nameStr` is set, data is automatically moved to local storage. * * * #### del Deletes specific data from storage. If `nameStr` is not set, only cached data is cleared. *Example:* ```javascript storage.del(storage.key.testStr) ``` * * * #### clear Clears all data within the current storage. `del` removes a specific key, while `clear` removes all keys. If `nameStr` is not set, only cached data is cleared. *Example:* ```javascript storage.clear() ``` ``` -------------------------------- ### Get Single Resource Source: https://mkframework.muzzik.cc/docs/module/asset/asset Use the get interface to load a single resource. Supports local, remote, and editor environments. Ensure correct path format and resource type. ```javascript get(pathStr_, type_, target_, config_?) ``` -------------------------------- ### Protobuf Message Structure Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Illustrates how the Websocket module can support arbitrary message formats like Protobuf, provided message ID and sequence can be parsed from the message body. ```protobuf enum MessageID { /** 测试消息 */ Test = 0; Test2 = 1; } message Package { /** 消息号 */ int32 id = 1; /** 消息序列号 */ int32 sequence = 2; /** 消息体 */ bytes data = 3; } // 后缀说明,C: 客户端发送消息,S:服务器返回消息,B:服务器推送消息 message TestC { int32 data = 1; } message TestS { int32 data = 1; } message Test2B { string data = 1; } ``` -------------------------------- ### get Source: https://mkframework.muzzik.cc/docs/module/asset/asset Loads a single resource, supporting local, remote, and editor environments. It handles path optimizations and can automatically add image suffixes based on the type. ```APIDOC ## get ### Description Loads a single resource, supporting local, remote, and editor environments. It handles path optimizations and can automatically add image suffixes based on the type. ### Method `get(pathStr_, type_, target_, config_?)` ### Parameters #### Path Parameters - **pathStr_** (string) - Required - Resource path. Can be a full path (e.g., `db://resources/test/image.png`) or a path within a bundle (e.g., `test/image.png`, requires `bundleStr` in config). - **type_** (string) - Required - Resource type (e.g., Prefab, SpriteFrame, Texture2D). The system may automatically append suffixes like `/spriteFrame` or `/texture` for image types. - **target_** (Node | TypeFollowReleaseObject | null) - Required - The object to which the resource's lifecycle is bound. If null, manual reference counting is required. #### Query Parameters - **config_** (object) - Optional - Loading configuration. - **bundleStr** (string) - The name of the bundle to load from. Defaults to 'resources' in the editor or the current scene's bundle at runtime. - **progressFunc** (function) - Callback function for loading progress. - **completedFunc** (function) - Callback function when loading is completed. - **remoteOption** (object) - Configuration for remote resources. - **retryNum** (number) - Number of times to retry loading on failure. Defaults to `GlobalConfig.Asset.Config.retryCountOnLoadFailureNum`. ``` -------------------------------- ### Get All Open Modules Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves a list of all currently open UI modules. ```typescript // 获取当前所有打开的 ViewBase 对象 const all = mk.uiManage.get(); ``` -------------------------------- ### getDir Source: https://mkframework.muzzik.cc/docs/module/asset/asset Loads all resources within a specified folder, supporting local and remote environments. Parameters are similar to the `get` method. ```APIDOC ## getDir ### Description Loads all resources within a specified folder, supporting local and remote environments. Parameters are similar to the `get` method. ### Method `getDir(pathStr_, type_, target_, config_?)` ### Parameters #### Path Parameters - **pathStr_** (string) - Required - The folder path for resources to load. - **type_** (string) - Required - The type of resources to load from the directory. - **target_** (Node | TypeFollowReleaseObject | null) - Required - The object to which the resources' lifecycle is bound. If null, manual reference counting is required. #### Query Parameters - **config_** (object) - Optional - Loading configuration, similar to `get` method (e.g., `bundleStr`, `progressFunc`, `completedFunc`, `remoteOption`, `retryNum`). ``` -------------------------------- ### Message ID Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Illustrates how to use JSON for communication with message IDs and sequence numbers, including custom codec and parsing functions. ```APIDOC ## WebSocket with Message IDs and JSON ### Description This example demonstrates communication using JSON data, including message IDs and sequence numbers. It involves creating a custom codec and specifying functions to parse these identifiers from message bodies. ### Steps 1. **Define Codec**: Create a custom codec class that implements `decode` and `encode` methods for JSON. ```javascript const codec = new (class extends mk.CodecBase { decode(data: string): Object { return JSON.parse(data); } encode(data: Object): string { return JSON.stringify(data); } })(); ``` 2. **Create Websocket Instance with Parsers**: Initialize `mk.network.Websocket` with the custom codec and parsing functions. ```javascript const ws = new mk.network.Websocket({ codec: codec, parseMessageIdFunc: (data: any) => data.id, parseMessageSequenceFunc: (data: any) => data.sequence, }); ``` 3. **Define Message Creation**: Implement a function to create messages with IDs and sequence numbers. ```javascript let messageSequenceNum = 0; const createMessageA = (data: number): any => { return { id: 0, sequence: messageSequenceNum++, data: data }; }; ``` 4. **Send and Listen**: Send messages using `send`, `request`, and `emit`, and listen for specific message IDs using `ws.message.on`. ```javascript const messageA2 = createMessageA(456); ws.message.on(0, (data) => { console.log('Listener received', data); }); ws.message.request(messageA2, -1)?.then((data) => { console.log('Request response', data); }); ws.message.emit(messageA2); ``` ``` -------------------------------- ### Get All Open Instances of a Module Type Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves a list of all open instances for a given module type. ```typescript // 获取所有打开的 Test 模块列表 const testList = mk.uiManage.get([Test]); ``` -------------------------------- ### Overlapping Audio Playback Example Source: https://mkframework.muzzik.cc/docs/module/audio/unit Demonstrates how to achieve overlapping audio playback by cloning an audio unit and playing from the stopped state of the cloned units. This allows for multiple instances of the same audio resource to play concurrently. ```typescript class Test extends mk.ViewBase { @property({ displayName: '重叠音效', type: mk.Audio_.Unit }) overlapEffect = new mk.Audio_.Unit(); /** 重叠音频数组 */ private _overlapEffectList!: mk.Audio_.Unit[]; // 通过 clone 得到多个音频单元 protected open(): void | Promise { this._overlapEffectList.push( this.overlapEffect, this.overlapEffect.clone(), this.overlapEffect.clone() ); // 或者如下 // this._overlapEffectList.push(this.overlapEffect, ...Array.from({ length: 2 }, (v, k) => this.overlapEffect.clone())); } // 获取停止状态的音频单元播放 clickAudio(): void { mk.audio.play(this._overlapEffectList.find((v) => v.state === mk.Audio_.State.Stop)!); } } ``` -------------------------------- ### Implement Custom Codec Source: https://mkframework.muzzik.cc/docs/module/other/codec Extend `mk.CodecBase` to define custom encode and decode methods. This example uses JSON for serialization. ```typescript class MyCodec extends mk.CodecBase { // 编码 encode(data: any): any { return JSON.stringify(data); } // 解码 decode(data: any): any { return JSON.parse(data); } } ``` -------------------------------- ### Get All Specific Type Instances of a Module Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves a list of all open instances of a module that match a specific type string. ```typescript // 获取所有打开的 Test 模块列表且模块类型为 default const panelOfTypeAList = mk.uiManage.get([Test], 'default'); ``` -------------------------------- ### Run Guide Source: https://mkframework.muzzik.cc/docs/module/guide/manage Execute the current step, automatically canceling pause status and updating the view. This is typically not called manually unless resuming a paused step. ```javascript run(): Promise ``` -------------------------------- ### Get Registration Data Function Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage A function that can be assigned to retrieve module registration data, used when `mk.uiManage.open` cannot find registration data. ```APIDOC ### getRegisDataFunc Function to get module registration data. If you don't want to use `mk.uiManage.regis` everywhere, you can assign a function to this property. It will be called when `mk.uiManage.open` cannot find registration data, based on the provided parameter (constructor type of `mk.ViewBase`). ``` -------------------------------- ### Define View for MVC Module Source: https://mkframework.muzzik.cc/docs/module/module/mvc Define a custom View by extending `mk.MVCViewBase` and specifying the Model type. Use `mk.uiManage` for registration and opening. Implement `open()` for UI setup and event binding, and `close()` for cleanup. ```typescript class MyModuleView extends mk.MVCViewBase { static async new() { mk.uiManage.regis(MyModuleView, 'db://assets/MyModule.prefab', null); return mk.uiManage.open(MyModuleView); } protected open() { console.log('View 打开'); this.node.getChildByName('按钮_关闭')!.once('click', () => this.close(), this); } close() { console.log('View 关闭'); mk.uiManage.unregis(MyModuleView); } } ``` -------------------------------- ### Get Data from Storage Source: https://mkframework.muzzik.cc/docs/module/data/storage Retrieve data using its key. If the data does not exist, it returns the default value defined in the constructor's 'data' property, or null if no default is set. ```javascript storage.get(storage.key.testStr) ``` -------------------------------- ### Message Sequence Number Example Source: https://mkframework.muzzik.cc/docs/module/network/websocket Illustrates the use of message sequence numbers to uniquely identify individual messages sent by the client, enabling correct matching of server responses. ```plaintext 1. 客户端 -> 消息 A(消息号 0, 序列号 0) -> 服务器 2. 客户端 -> 消息 A(消息号 0, 序列号 1) -> 服务器 3. 服务器 -> 消息 A 结果(消息号 0, 序列号 0) -> 客户端 ``` -------------------------------- ### mk.Storage Initialization Source: https://mkframework.muzzik.cc/docs/module/data/storage Demonstrates how to create a new Storage instance with initial data and configuration. ```APIDOC ## Class: mk.Storage ### Description Used for saving data locally. It can be used to store player accounts, last selected characters, etc. ### Initialization ```javascript class StorageData { /** Test data */ testStr = ''; } let storage = new mk.Storage({ nameStr: 'Storage Name', data: new StorageData(), }); ``` ### Initialization Parameters | Property | Description | |---|---| | `nameStr` (string, optional) | The name of the storage. If not provided, data is temporarily stored in memory. | | `data` (object, optional) | Initial data for the storage. | | `codec` (object, optional) | A codec for encrypting/decrypting stored data. | | `writeIntervalMsNum` (number, optional) | Write interval in milliseconds. Prevents frequent writes that might cause stuttering. | ``` -------------------------------- ### 传递初始化数据 Source: https://mkframework.muzzik.cc/docs/module/guide/step 在调用 `guideManage.setStep` 时,可以传递初始化数据。此数据可以通过 `initData` 属性在步骤内部访问。 ```typescript guideManage.setStep(1, { userLevel: 5 }); ``` -------------------------------- ### Register and Open Module Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Demonstrates the common workflow of registering a module via its resource path and then opening it. ```typescript // 手动注册 await mk.uiManage.regis(Test, 'Module/Test/Test.prefab', this); // 打开 const test = await mk.uiManage.open(Test, { init: { id: 1 } }); // 关闭并销毁最近打开的 Test await mk.uiManage.close(Test, { isDestroy: true }); ``` -------------------------------- ### 创建引导步骤基类 Source: https://mkframework.muzzik.cc/docs/module/guide/step 创建一个通用的引导步骤基类,继承自 `mk.GuideStepBase`。此步骤可忽略如果未使用操作表。 ```typescript // 示例:引导步骤基类 export abstract class XXXGuideStepBase extends mk.GuideStepBase {} ``` -------------------------------- ### Initialize Object Pool Source: https://mkframework.muzzik.cc/docs/module/other/object-pool Demonstrates the basic initialization of an object pool. The same parameters apply to both asynchronous and synchronous pools. ```javascript const pool = new mk.ObjectPool({ // Here are the initialization parameters }); ``` -------------------------------- ### Get Last Opened Module Instance Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves the most recently opened instance of a specific module type. ```typescript // 获取最后打开的 Test 模块 const test = mk.uiManage.get(Test); ``` -------------------------------- ### 在步骤内跳转 Source: https://mkframework.muzzik.cc/docs/module/guide/step 在引导步骤内部,可以通过 `this.guideManage.setStep()` 方法手动跳转到其他步骤。 ```typescript this.guideManage.setStep(2); // 手动跳转到其他步骤 ``` -------------------------------- ### Get Specific Type Instance of a Module Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Retrieves the most recently opened instance of a module with a specific type string. ```typescript // 获取最后打开的 Test 模块且模块类型为 default const panelOfTypeA = mk.uiManage.get(Test, 'default'); ``` -------------------------------- ### Create Data Sharer Instance Source: https://mkframework.muzzik.cc/docs/module/data/sharer Instantiate the data sharer with a class that defines the data structure. This sets up the default values for the shared data. ```javascript class Data { test = 1; } let data = mk.dataSharer(Data); ``` -------------------------------- ### 创建引导步骤类型 Source: https://mkframework.muzzik.cc/docs/module/guide/step 让具体的引导步骤继承基类并实现相应的逻辑。此代码定义了一个具体的引导步骤类 `XXXGuideStepA`。 ```typescript @cclass class XXXGuideStepA extends XXXGuideStepBase { // 实现具体步骤逻辑 ... } ``` -------------------------------- ### Get Shared Data (Synchronous) Source: https://mkframework.muzzik.cc/docs/module/data/sharer Retrieve the current value of a piece of shared data synchronously. This is the most straightforward way to access data. ```javascript let a = data.test ``` -------------------------------- ### Define Storage Data and Create Storage Instance Source: https://mkframework.muzzik.cc/docs/module/data/storage Define a class for your storage data structure and then create a new mk.Storage instance. The 'nameStr' parameter is optional but recommended for persistent local storage; without it, data is temporarily stored in memory. ```javascript class StorageData { /** 测试数据 */ testStr = ''; } let storage = new mk.Storage({ nameStr: '存储器名字', data: new StorageData(), }); ``` -------------------------------- ### Listen to UI Module Events Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Sets up event listeners for module open and close events, logging the key and instance to the console. ```typescript mk.uiManage.event.on(mk.uiManage.event.key.open, (key, instance) => { console.log('opened:', key.name, instance); }); mk.uiManage.event.on(mk.uiManage.event.key.close, (key, instance) => { console.log('closed:', key.name, instance); }); ``` -------------------------------- ### Open Module with Initialization Data Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Opens a module, providing initialization data and specifying the module type. ```typescript const test = await mk.uiManage.open(Test, { init: { id: 1 }, type: 'default' }); ``` -------------------------------- ### Get Texture Data Source: https://mkframework.muzzik.cc/docs/module/language/manage Retrieves multilingual image data, returning a SpriteFrame object. Allows specifying language and a target object for resource management. ```APIDOC ## getTexture ### Description Get the specified multilingual image. ### Syntax ``` mk.languageManage.getTexture('多语言类型名', '示例', null, GlobalConfig.Language.types.zhCn); ``` ### Parameters | Parameter | Type | Description | |---|---|---| | `type` | `string` | The multilingual type name passed during `addTexture` | | `markStr` | `string` | The multilingual identifier (object key) of the `addTexture` data | | `target` | `object` | Object for resource release with resource | | `language` | `string` | Language (optional, defaults to the current `typeStr`) | ### Return Value The corresponding `SpriteFrame` object. ``` -------------------------------- ### Create Websocket Instance Source: https://mkframework.muzzik.cc/docs/module/network/websocket Instantiate a Websocket object for network communication. Configure options like codec, send intervals, reconnect settings, timeouts, and heartbeat. ```typescript const ws = new mk.network.Websocket({ // codec:消息体编解码器 // sendIntervalMsNum:发送间隔(毫秒),防止一帧内发送多次 // reconnectIntervalMsNum:重连间隔(毫秒),默认 1000 // maxReconnectNum:最大重连次数,默认 5 // waitTimeoutMsNum:等待消息超时时间(毫秒),默认 5000 // heartbeatConfig:心跳配置 // parseMessageIdFunc(data: any):消息号解析函数,参数为消息体 // parseMessageSequenceFunc(data: any):消息序列号解析函数,参数为消息体 }); // 微信下可使用 new mk.network.WebsocketWX ``` -------------------------------- ### Get Label Data Source: https://mkframework.muzzik.cc/docs/module/language/manage Retrieves multilingual text data based on the provided type, mark, and optional configuration. Supports dynamic parameter replacement. ```APIDOC ## getLabel ### Description Get the specified multilingual text. ### Syntax ``` mk.languageManage.getLabel('多语言类型名', '示例', { language: GlobalConfig.Language.types.zhCn, argsStrList: ['123'], }); ``` ### Parameters | Parameter | Type | Description | |---|---|---| | `type` | `string` | The multilingual type name passed during `addLabel` | | `markStr` | `string` | The multilingual identifier (object key) of the `addLabel` data | | `config` | `object` | Optional configuration | | `config.language` | `string` | Language (defaults to the current `typeStr`) | | `config.argsStrList` | `string[]` | Multilingual parameters | ### Return Value The corresponding multilingual text (e.g., `示例-123`). ``` -------------------------------- ### Open Module Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Opens a module. The module must have been previously registered via `regis` or have its registration data available via `getRegisDataFunc`. ```APIDOC ## open `open(key, config?) : Promise` Opens a module. Requires the module to have been registered via `regis` or have registration data available via `getRegisDataFunc`. ### Parameters * `key` (Constructor): The module type. * `config` (optional): Opening configuration. * `config.init` (any): Initialization data, matching the type of the `initData` property of the `key` type. * `config.type` (string): The module type. Defaults to "default". * `config.parent` (Node): The parent node for the module. ### Key Points * You can call `open` immediately after `regis` without waiting for `regis` to complete. ### Example ``` const test = await mk.uiManage.open(Test, { init: { id: 1 }, type: 'default' }); ``` ``` -------------------------------- ### 不依赖组件更新文本 (mk.languageManage.getLabel) Source: https://mkframework.muzzik.cc/docs/module/language/label 直接使用 `mk.languageManage.getLabel` 方法获取格式化后的多语言文本,无需挂载到特定组件。此方法接收类型名、语言标识和包含参数的对象。 ```javascript let comp = node.getComponent(Label)! comp.string = mk.languageManage.getLabel('多语言类型名', '示例', { argsStrList: ['123'], }); ``` -------------------------------- ### Websocket Constructor Source: https://mkframework.muzzik.cc/docs/module/network/websocket Initializes a new Websocket instance with various configuration options for message handling, intervals, timeouts, and heartbeat. ```APIDOC ## new mk.network.Websocket() ### Description Creates a new network object for communication via WebSocket. ### Parameters * `codec` (object) - Optional - Message body codec for encoding and decoding. * `sendIntervalMsNum` (number) - Optional - Send interval in milliseconds to prevent multiple sends within a single frame. * `reconnectIntervalMsNum` (number) - Optional - Reconnection interval in milliseconds (defaults to 1000). * `maxReconnectNum` (number) - Optional - Maximum number of reconnection attempts (defaults to 5). * `waitTimeoutMsNum` (number) - Optional - Message waiting timeout in milliseconds (defaults to 5000). * `heartbeatConfig` (object) - Optional - Heartbeat configuration. * `parseMessageIdFunc` (function) - Optional - Function to parse the message ID from the message body. * `parseMessageSequenceFunc` (function) - Optional - Function to parse the message sequence number from the message body. ``` -------------------------------- ### Module Registration Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Registers a module with the UI Manager, initializing its object pool and preloading resources. ```APIDOC ## regis `regis(key, source, target?, config?) : Promise` Registers a module and initializes its object pool. ### Parameters * `key` (Constructor): The module type. * `source` (Prefab | string | Node | Record): The source of the registration resource. * `target` (optional): The object that will control the resource's release. * `config` (optional): Registration configuration. * `config.isRepeat` (boolean): Whether this module can be created multiple times. Defaults to false. * `config.parent` (Node): The default parent node for this module. Defaults to the canvas node or scene if not found. * `config.loadConfig` (object): Configuration passed to `mk.asset.get` when loading resources. * `config.poolMinHoldNum` (number): Minimum number of objects to hold in the object pool (expands when insufficient). Defaults to `isRepeat ? 8 : 1`. * `config.poolMaxHoldNum` (number): Maximum number of objects to hold in the object pool (-1 to disable). Defaults to -1. * `config.poolInitFillNum` (number): Initial number of objects to fill in the object pool. Defaults to 1. ### Key Points * `source` can be a Record object to specify different resource sources for different types (see example). * If `target` is provided, `unregis(key)` will be triggered when `target` is released. ### Example ``` // Register Test module via resource path await mk.uiManage.regis(Test, 'Module/Test/Test111.prefab', this); // Register multi-type Test module via resource path await mk.uiManage.regis( Test, { default: 'Module/Test/Test111.prefab', type2: 'Module/Test/Test222.prefab', }, this ); ``` ``` -------------------------------- ### 单路径步骤跳转 Source: https://mkframework.muzzik.cc/docs/module/guide/step 使用 `_next()` 方法跳转到下一个步骤。此方法仅在 `nextStepNumList` 长度为 1 时可用,并可传递初始化数据给下一个步骤。 ```typescript this._next({ completed: true }); ``` -------------------------------- ### Websocket with JSON and Message IDs Source: https://mkframework.muzzik.cc/docs/module/network/websocket Configure Websocket for JSON communication by providing custom codec and functions to parse message IDs and sequences from the message body. This example demonstrates sending, requesting, and emitting messages with specific IDs. ```typescript // 创建编解码器,收到的数据会解码为 Object,发送的数据编码为 JSON const codec = new (class extends mk.CodecBase { decode(data: string): Object { return JSON.parse(data); } encode(data: Object): string { return JSON.stringify(data); } })(); // 创建网络对象 const ws = new mk.network.Websocket({ codec: codec, // 从消息体解析得到消息号 parseMessageIdFunc: (data: any) => { return data.id; }, // 从消息体解析得到消息序列号 parseMessageSequenceFunc: (data: any) => { return data.sequence; }, }); /** 消息序列号 */ let messageSequenceNum = 0; /** 创建消息 A */ const createMessageA = (data: number): any => { return { // 消息号 0 代表消息 A,创建其他消息则递增 id: 0, // 消息序列号自增代表发送批次 sequence: messageSequenceNum++, // 消息数据 data: data, }; }; const messageA = createMessageA(123); const messageA2 = createMessageA(456); // 监听消息号为 0 的消息接收数据 ws.message.on(0, (data) => { console.log('监听返回', data); }); // 发送 messageA2 消息等待服务器返回 ws.message.request(messageA2, -1)?.then((data) => { console.log('请求返回', data); }); // 模拟服务器发送 messageA 数据,触发监听返回(消息号一致) ws.message.emit(messageA); // 模拟服务器发送 messageA2 数据,触发监听返回(消息号一致)和请求返回(消息序列号一致) ws.message.emit(messageA2); ``` -------------------------------- ### 添加多语言类型 (mk.languageManage.addLabel) Source: https://mkframework.muzzik.cc/docs/module/language/label 使用 `addLabel` 方法注册一个新的多语言类型。第一个参数是类型名,第二个参数是包含不同语言文本的对象,键为语言标识,值为文本模板。支持参数化文本,如 "template-{0}"。 ```javascript mk.languageManage.addLabel('多语言类型名', { 示例: { enUs: 'template-{0}', zhCn: '示例-{0}', }, }); ``` -------------------------------- ### 在View中注册生命周期监视器 Source: https://mkframework.muzzik.cc/docs/module/module/mvvm 演示了如何在View中使用`mk.monitor.on`注册监视器,并将`target`设置为`this`,以便框架在`close`时自动清理。这有助于降低内存泄漏风险。 ```javascript mk.monitor.on(this.data, 'label', handler, this); // target=this,框架会自动 clear ``` -------------------------------- ### 使用 LabelData 类添加多语言文本 Source: https://mkframework.muzzik.cc/docs/module/language/manage 通过 `mk.Language_.LabelData` 构造函数添加多语言文本,提供类型安全和 key 属性。 ```javascript export default new mk.Language_.LabelData(cc.js.getClassName(XXX), { 示例: { enUs: 'template-{0}', zhCn: '示例-{0}', }, }); ``` -------------------------------- ### 注册引导步骤 Source: https://mkframework.muzzik.cc/docs/module/guide/step 使用引导管理器的 `regis` 方法注册引导步骤。支持注册通过 `new` 实例化的对象或节点组件对象。 ```typescript // 使用 new 的对象注册 guideManage.regis([new XXXGuideStepA(), ...]); // 使用节点组件对象注册 guideManage.regis([node.getComponent(XXXGuideStepA), ...]); ``` -------------------------------- ### 在代码中使用组件更新文本 Source: https://mkframework.muzzik.cc/docs/module/language/label 通过获取 `mk.language.Label` 组件实例,然后修改 `typeStr`, `markStr`, 和 `argsStrList` 属性来更新组件显示的文本。注意 `argsStrList` 需要重新赋值才会触发更新。 ```javascript let comp = node.getComponent(mk.language.Label)! comp.typeStr = '多语言类型名'; comp.markStr = '示例'; comp.argsStrList = ['123']; ``` -------------------------------- ### 预加载资源 Source: https://mkframework.muzzik.cc/docs/module/guide/step 在进入当前步骤之前,`preLoad` 生命周期函数会被调用,可用于提前加载资源或初始化数据。此示例展示了异步加载资源。 ```typescript preLoad?(): void | Promise { await preloadAssets(); } ``` -------------------------------- ### 动态添加多语言文本 Source: https://mkframework.muzzik.cc/docs/module/language/manage 使用 `addLabel` 方法动态添加多语言文本数据,可包含参数占位符。 ```javascript mk.languageManage.addLabel('多语言类型名', { 示例: { enUs: 'template-{0}', zhCn: '示例-{0}', }, }); ``` -------------------------------- ### 监听语言切换事件 Source: https://mkframework.muzzik.cc/docs/module/language/manage 通过 `mk.languageManage.event` 监听 `switchLanguage` 事件,实现语言切换时的实时更新。 ```javascript mk.languageManage.event.on(mk.languageManage.event.key.switchLanguage, () => { console.log('语言已切换'); }); ``` -------------------------------- ### 列表渲染数据更新 Source: https://mkframework.muzzik.cc/docs/module/module/mvvm 展示了Control如何更新列表数据,并通过View的公开方法传入新数组以触发UI更新。 ```javascript this._view.applyModelSnapshot({ items: [...this._model.items] }) ``` -------------------------------- ### 文本数据表示例 Source: https://mkframework.muzzik.cc/docs/module/language/manage 展示了 `labelDataTab` 中文本数据的格式,包含不同语种的文本。 ```json { "测试": { "zhCn": "测试", "enUs": "Test" } } ``` -------------------------------- ### 获取多语言文本 Source: https://mkframework.muzzik.cc/docs/module/language/manage 使用 `getLabel` 方法获取指定的多语言文本,支持参数替换和指定语种。 ```javascript mk.languageManage.getLabel('多语言类型名', '示例', { language: GlobalConfig.Language.types.zhCn, argsStrList: ['123'], }); ``` -------------------------------- ### 获取操作单元结果 Source: https://mkframework.muzzik.cc/docs/module/guide/step 通过 `operateTab` 属性可以获取已加载操作单元的 `load` 方法的返回值。此示例获取了引导窗口操作单元的结果。 ```typescript const windowRef = this.operateTab[XXXGuideOperate.key.引导窗口]; ``` -------------------------------- ### 动态添加多语言纹理 Source: https://mkframework.muzzik.cc/docs/module/language/manage 使用 `addTexture` 方法动态添加多语言纹理(图片)数据。 ```javascript mk.languageManage.addTexture('多语言类型名', { 示例: { zhCn: 'db://assets/resources/xxx.png', enUs: 'db://assets/resources/xxx_en.png', }, }); ``` -------------------------------- ### 获取多语言纹理 Source: https://mkframework.muzzik.cc/docs/module/language/manage 使用 `getTexture` 方法获取指定的多语言纹理(图片)资源。 ```javascript mk.languageManage.getTexture('多语言类型名', '示例', null, GlobalConfig.Language.types.zhCn); ``` -------------------------------- ### 加载步骤UI Source: https://mkframework.muzzik.cc/docs/module/guide/step 当进入当前步骤时,`load` 生命周期函数会被调用。此示例展示了根据是否跳转来显示过渡效果,并初始化UI。 ```typescript async load(isJump_: boolean) { if (isJump_) { this.showTransitionEffect(); } this.initUI(); } ``` -------------------------------- ### 定义后续步骤(单路径) Source: https://mkframework.muzzik.cc/docs/module/guide/step 当 `nextStepNumList` 数组长度为 1 时,支持 `this._next()` 自动跳转到下一个步骤,并触发预加载。 ```typescript nextStepNumList = [2]; // 单路径 ``` -------------------------------- ### 切换当前语种 Source: https://mkframework.muzzik.cc/docs/module/language/manage 通过修改 `mk.languageManage.typeStr` 属性来切换当前的多语言语种。 ```javascript // 切换到英文(美国) mk.languageManage.typeStr = GlobalConfig.Language.types.enUs; ``` -------------------------------- ### 定义后续步骤(多路径) Source: https://mkframework.muzzik.cc/docs/module/guide/step 当 `nextStepNumList` 数组长度大于 1 时,仅触发预加载,不支持 `this._next()` 自动跳转,适用于多分支引导。 ```typescript nextStepNumList = [2, 3]; // 多路径(仅预加载) ``` -------------------------------- ### Event Handling Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Provides an event object for listening to module open and close events. ```APIDOC ### event UI event object, providing the following events: | Event Name | Parameters | Description | |---|---|---| | open | (key: mk.UIManage.TypeOpenKey, module_: any) | Triggered after a module is successfully opened. | | close | (key: mk.UIManage.TypeOpenKey, module_: any) | Triggered after a module is successfully closed. | **Usage Example:** ``` mk.uiManage.event.on(mk.uiManage.event.key.open, (key_: mk.UIManage_.TypeOpenKey, module_: any) => { // ... handle module open event }, this); ``` ``` -------------------------------- ### 配置默认语言类型 Source: https://mkframework.muzzik.cc/docs/module/language/manage 通过 `defaultTypeStr` 配置默认语言类型,可设置为特定类型或自动匹配。 ```javascript // 默认为中文 defaultTypeStr = types.zhCn; // 根据地区动态匹配默认语言 defaultTypeStr = 'auto'; ``` -------------------------------- ### 卸载步骤资源 Source: https://mkframework.muzzik.cc/docs/module/guide/step 当离开当前步骤时,`unload` 生命周期函数会被调用,用于清理资源、销毁UI和取消事件监听。此示例展示了销毁UI。 ```typescript async unload() { this.destroyUI(); } ``` -------------------------------- ### Register Module with Resource Path Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Registers a module using its resource path. The `this` context is used as the target for resource release. ```typescript await mk.uiManage.regis(Test, 'Module/Test/Test111.prefab', this); ``` -------------------------------- ### 获取 LabelData 的 key Source: https://mkframework.muzzik.cc/docs/module/language/manage 通过 `labelData.key` 属性快速获取多语言标识,方便在代码中使用。 ```javascript const key = labelData.key.示例; ``` -------------------------------- ### Listen to UI Open/Close Events Source: https://mkframework.muzzik.cc/docs/module/module/ui/ui-manage Attach event listeners to monitor when UI modules are opened or closed. The `this` context is bound to the listener. ```typescript mk.uiManage.event.on(mk.uiManage.event.key.open, (key_: mk.UIManage_.TypeOpenKey, module_: any) => { ... }, this) ``` -------------------------------- ### 设置场景 Source: https://mkframework.muzzik.cc/docs/module/guide/step 通过 `sceneStr` 属性指定步骤需要加载的场景。如果当前场景不匹配,管理器会自动切换场景。 ```typescript sceneStr = 'resources.lobby'; ``` -------------------------------- ### 全局配置屏幕适配类型 Source: https://mkframework.muzzik.cc/docs/module/other/adaptation 通过修改全局配置中的 `adaptationType` 来设置屏幕适配模式。框架将自动应用所选的适配类型。 ```typescript namespace GlobalConfig { ... export namespace View { ... /** 适配类型 */ export const adaptationType: AdaptationMode = AdaptationMode.Adaptive; } } ```