Skip to content
TeleportService

Service / TeleportService

TeleportService Class

Multiple scene and delivery services

Table of contents

Methods

asyncGetPlayerRoomInfo(userId: string): Promise<RoomInfo> other
Get the room information of the designated Player
asyncTeleportToRoom(roomId: string, userIds: string[], options?: TeleportOptions): Promise<TeleportResult> other
Asynchronous transfer to specified room
asyncTeleportToScene(sceneName: string, userIds: string[], options?: TeleportOptions): Promise<TeleportResult> other
Asynchronous transfer to the specified scene of the current game
getSourceInfo(teleportId: string): RoomInfo other
Obtain the source information of the transmission
getTeleportData(teleportId: string): TeleportData other
Retrieve the data set in TeleportOptions when calling the transport interface

Methods

asyncGetPlayerRoomInfo

Static asyncGetPlayerRoomInfo(userId): Promise<RoomInfo> other

Get the room information of the designated Player

Parameters

userId stringUsage: target Player's userId range: depends on the length of the userId

Returns

Promise<RoomInfo>Specify the room information of the Player

Example usage: Create a script called "ServerScript" and place it in the scene. The code is as follows:

ts
@Component
export default class Server extends Script {
    protected onStart(): void {
        // The transmission function needs to be initiated on the server side, and using it on the client side will result in an error
        if (SystemUtil.isServer()) {
            Player.onPlayerJoin.add((player: Player) => {
                // When the player joins, the teleportation will be initiated after a countdown of 5 seconds
                setTimeout(() => {
                    // Suppose we want to send it to the room of the Player whose UserId is "123456" to play together
                    const targetUserId: string = "123456";
                    // First, use asyncGetLayerRoomInfo to obtain the room information where the player is located
                    TeleportService.asyncGetPlayerRoomInfo(targetUserId).then((roomInfo) => {
                        // Get RoomId
                        const roomId: string = roomInfo.roomId;
                        // Add the Player to be transferred to the new scene into the array
                        const playerToTeleport: string[] = [player.userId];
                        // Can be filled with additional data to be carried
                        const opt: TeleportOptions = {
                            teleportData: "This is test data."
                        }
                        // Call API and transfer it to the target room
                        TeleportService.asyncTeleportToRoom(roomId, playerToTeleport, opt);
                    });
                }, 5 * 1000);
            });
        }
    }
}
@Component
export default class Server extends Script {
    protected onStart(): void {
        // The transmission function needs to be initiated on the server side, and using it on the client side will result in an error
        if (SystemUtil.isServer()) {
            Player.onPlayerJoin.add((player: Player) => {
                // When the player joins, the teleportation will be initiated after a countdown of 5 seconds
                setTimeout(() => {
                    // Suppose we want to send it to the room of the Player whose UserId is "123456" to play together
                    const targetUserId: string = "123456";
                    // First, use asyncGetLayerRoomInfo to obtain the room information where the player is located
                    TeleportService.asyncGetPlayerRoomInfo(targetUserId).then((roomInfo) => {
                        // Get RoomId
                        const roomId: string = roomInfo.roomId;
                        // Add the Player to be transferred to the new scene into the array
                        const playerToTeleport: string[] = [player.userId];
                        // Can be filled with additional data to be carried
                        const opt: TeleportOptions = {
                            teleportData: "This is test data."
                        }
                        // Call API and transfer it to the target room
                        TeleportService.asyncTeleportToRoom(roomId, playerToTeleport, opt);
                    });
                }, 5 * 1000);
            });
        }
    }
}

asyncTeleportToRoom

Static asyncTeleportToRoom(roomId, userIds, options?): Promise<TeleportResult> other

Asynchronous transfer to specified room

Parameters

roomId stringUsage: target game Id to be transferred default: undefined range: determine according to the length of roomid
userIds string[]Usage: array of player userIDs to be transmitted default: undefined range: determined by the length of the room
options? TeleportOptionsUsage: Optional additional transmission information The createNewPrivateeRoom parameter is not supported. If it is set to true, it will not create a new room default: undefined

Returns

Promise<TeleportResult>If the request is normal, return 'resolve'; if it is abnormal, return 'reject'

Precautions

If the designated room does not exist or cannot accommodate enough people, it will fail. The more players participate in teleportation, the higher the failure rate

Precautions

The 'create NewPrivate Room' parameter is not supported, and setting it to 'true' will not create a new room

Example usage: Create a script called "TeleportScript", place it in the scene, and set it as dual ended. The code is as follows:

Parameters

gameIdstring
userIdsstring[]
sceneName?string
options?TeleportOptions

Returns

Promise<TeleportResult>
ts
@Component
export default class TeleportScript extends Script {
    protected onStart(): void {
        // Server logic
        if (SystemUtil.isServer()) {
            Player.onPlayerJoin.add((player: Player) => {
                // When a player joins, the teleportation will be initiated after a countdown of 5 seconds to avoid immediate teleportation and make it difficult to observe
                setTimeout(() => {
                    // Suppose we want to send it to the room of the Player whose UserId is "123456" to play together
                    const targetUserId: string = "123456";
                    // First, use asyncGetLayerRoomInfo to obtain the room information where the player is located
                    TeleportService.asyncGetPlayerRoomInfo(targetUserId).then((roomInfo) => {
                        // Get RoomId
                        const roomId: string = roomInfo.roomId;
                        // Add the Player to be transferred to the new scene into the array
                        const playerToTeleport: string[] = [player.userId];
                        // Can be filled with additional data to be carried
                        const opt: TeleportOptions = {
                            teleportData: "This is test data."
                        }

                        // Declare callback functions for success and failure, used to handle the callback results of the transport interface.
                        // Successful situations generally do not require handling and will continue with the subsequent jump process.
                        // If it fails, it may be due to timeout or error, and information can be read from the callback data for further processing.
                        const onSuccess = () => { }
                        const onFailed = (result: mw.TeleportResult) => {
                            switch (result.status) {
                                case mw.TeleportStatus.success:
                                    break;
                                case mw.TeleportStatus.ignored:
                                    // Triggered too frequently, this request was ignored
                                    break;
                                case mw.TeleportStatus.timeout:
                                    // If the timeout period expires, you can choose to retry the transmission or prompt the Player
                                    break;
                                case mw.TeleportStatus.error:
                                    // Send error messages to all participating clients
                                    for (const userId in result.userIds) {
                                        const player = Player.getPlayer(userId)
                                        if (player) {
                                            Event.dispatchToClient(player, "TeleportResult", result);
                                        }
                                    }
                            }
                        };

                        // The transmission function needs to be initiated on the server side, and using it on the client side will result in an error
                        TeleportService.asyncTeleportToRoom(roomId, playerToTeleport, opt).then(onSuccess, onFailed);
                    }).catch((error: Error) => {
                        console.error(`getPlayerRoomInfo has error: ${error.message}`);
                    })
                }, 5 * 1000);
            });

#### Parameters

| `roomId` `string` | Usage: target game Id to be transferred default: undefined range: determine according to the length of roomid |
| :------ | :------ |
| `userIds` `string`[] | Usage: array of player userIDs to be transmitted default: undefined range: determined by the length of the room |
| `options?` [`TeleportOptions`](../interfaces/mw.TeleportOptions.md) | Usage: Optional additional transmission information The createNewPrivateeRoom parameter is not supported. If it is set to true, it will not create a new room default: undefined |

#### Returns

| `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> | If the request is normal, return 'resolve'; if it is abnormal, return 'reject' |
| :------ | :------ |

___

### asyncTeleportToScene <Score text="asyncTeleportToScene" /> 

`Static` **asyncTeleportToScene**(`sceneName`, `userIds`, `options?`): `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> <Badge type="tip" text="other" />

Asynchronous transfer to the specified scene of the current game

#### Parameters

| `sceneName` `string` | Usage: Target scene name to be transmitted default: range: Depending on the scene name |
| :------ | :------ |
| `userIds` `string`[] | Usage: Player userId array to transfer default: range: array size customize |
| `options?` [`TeleportOptions`](../interfaces/mw.TeleportOptions.md) | Usage: optional additional transmission information default: undefined |

#### Returns

| `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> | If the request is normal, return 'resolve'; if it is abnormal, return 'reject' |
| :------ | :------ |

::: warning Precautions

Only transfer between scene of the current game. If the scene name does not exist, the transfer will fail

:::

Usage example: create a scene named "Scene1" in the editor. Create a script named TeleportScript, place it in the scene, and set it as double ended. The code is as follows:
@Component
export default class TeleportScript extends Script {
    protected onStart(): void {
        // Server logic
        if (SystemUtil.isServer()) {
            Player.onPlayerJoin.add((player: Player) => {
                // When a player joins, the teleportation will be initiated after a countdown of 5 seconds to avoid immediate teleportation and make it difficult to observe
                setTimeout(() => {
                    // Suppose we want to send it to the room of the Player whose UserId is "123456" to play together
                    const targetUserId: string = "123456";
                    // First, use asyncGetLayerRoomInfo to obtain the room information where the player is located
                    TeleportService.asyncGetPlayerRoomInfo(targetUserId).then((roomInfo) => {
                        // Get RoomId
                        const roomId: string = roomInfo.roomId;
                        // Add the Player to be transferred to the new scene into the array
                        const playerToTeleport: string[] = [player.userId];
                        // Can be filled with additional data to be carried
                        const opt: TeleportOptions = {
                            teleportData: "This is test data."
                        }

                        // Declare callback functions for success and failure, used to handle the callback results of the transport interface.
                        // Successful situations generally do not require handling and will continue with the subsequent jump process.
                        // If it fails, it may be due to timeout or error, and information can be read from the callback data for further processing.
                        const onSuccess = () => { }
                        const onFailed = (result: mw.TeleportResult) => {
                            switch (result.status) {
                                case mw.TeleportStatus.success:
                                    break;
                                case mw.TeleportStatus.ignored:
                                    // Triggered too frequently, this request was ignored
                                    break;
                                case mw.TeleportStatus.timeout:
                                    // If the timeout period expires, you can choose to retry the transmission or prompt the Player
                                    break;
                                case mw.TeleportStatus.error:
                                    // Send error messages to all participating clients
                                    for (const userId in result.userIds) {
                                        const player = Player.getPlayer(userId)
                                        if (player) {
                                            Event.dispatchToClient(player, "TeleportResult", result);
                                        }
                                    }
                            }
                        };

                        // The transmission function needs to be initiated on the server side, and using it on the client side will result in an error
                        TeleportService.asyncTeleportToRoom(roomId, playerToTeleport, opt).then(onSuccess, onFailed);
                    }).catch((error: Error) => {
                        console.error(`getPlayerRoomInfo has error: ${error.message}`);
                    })
                }, 5 * 1000);
            });

#### Parameters

| `roomId` `string` | Usage: target game Id to be transferred default: undefined range: determine according to the length of roomid |
| :------ | :------ |
| `userIds` `string`[] | Usage: array of player userIDs to be transmitted default: undefined range: determined by the length of the room |
| `options?` [`TeleportOptions`](../interfaces/mw.TeleportOptions.md) | Usage: Optional additional transmission information The createNewPrivateeRoom parameter is not supported. If it is set to true, it will not create a new room default: undefined |

#### Returns

| `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> | If the request is normal, return 'resolve'; if it is abnormal, return 'reject' |
| :------ | :------ |

___

### asyncTeleportToScene <Score text="asyncTeleportToScene" /> 

`Static` **asyncTeleportToScene**(`sceneName`, `userIds`, `options?`): `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> <Badge type="tip" text="other" />

Asynchronous transfer to the specified scene of the current game

#### Parameters

| `sceneName` `string` | Usage: Target scene name to be transmitted default: range: Depending on the scene name |
| :------ | :------ |
| `userIds` `string`[] | Usage: Player userId array to transfer default: range: array size customize |
| `options?` [`TeleportOptions`](../interfaces/mw.TeleportOptions.md) | Usage: optional additional transmission information default: undefined |

#### Returns

| `Promise`<[`TeleportResult`](../interfaces/mw.TeleportResult.md)\> | If the request is normal, return 'resolve'; if it is abnormal, return 'reject' |
| :------ | :------ |

::: warning Precautions

Only transfer between scene of the current game. If the scene name does not exist, the transfer will fail

:::

Usage example: create a scene named "Scene1" in the editor. Create a script named TeleportScript, place it in the scene, and set it as double ended. The code is as follows:

@Component export default class TeleportScript extends Script { protected onStart(): void { // Server logic if (SystemUtil.isServer()) { Player.onPlayerJoin.add((player: Player) => { // When a player joins, the teleportation will be initiated after a countdown of 5 seconds to avoid immediate teleportation and make it difficult to observe setTimeout(() => { // Assuming a scene named 'Scene1' has already been created in the editor const sceneName: string = "Scene1"; // Add the Player to be transferred to the new scene into the array const playerToTeleport: string[] = [player.userId]; // Can be filled with additional data to be carried const opt: TeleportOptions = { teleportData: "This is test data." }

                // Declare callback functions for success and failure, used to handle the callback results of the transport interface.
                // Successful situations generally do not require handling and will continue with the subsequent jump process.
                // If it fails, it may be due to timeout or error, and information can be read from the callback data for further processing.
                const onSuccess = () => `{ }`
                const onFailed = (result: mw.TeleportResult) => {
                    switch (result.status) {
                        case mw.TeleportStatus.success:
                            break;
                        case mw.TeleportStatus.ignored:
                            // Triggered too frequently, this request was ignored
                            break;
                        case mw.TeleportStatus.timeout:
                            // If the timeout period expires, you can choose to retry the transmission or prompt the Player
                            break;
                        case mw.TeleportStatus.error:
                            // Send error messages to all participating clients
                            for (const userId in result.userIds) {
                                const player = Player.getPlayer(userId)
                                if (player) {
                                    Event.dispatchToClient(player, "TeleportResult", result);
                                }
                            }
                    }
                };

                // The transmission function needs to be initiated on the server side, and using it on the client side will result in an error
                TeleportService.asyncTeleportToScene(sceneName, playerToTeleport, opt).then(onSuccess, onFailed);
            }, 5 * 1000);
        });
    } else {
        // Client logic
        Event.addServerListener("TeleportResult", (result: mw.TeleportResult) => {
            console.error(`Teleport has error:`);
            console.error(`errorCode: $`{result.errorCode}``);
            console.error(`message: $`{result.message}``);
        });
    }
}

}

ts
___

### getSourceInfo <Score text="getSourceInfo" /> 

`Static` **getSourceInfo**(`teleportId`): [`RoomInfo`](../interfaces/mw.RoomInfo.md) <Badge type="tip" text="other" />

Obtain the source information of the transmission

#### Parameters

| `teleportId` `string` | Usage: The transmission ID to be queried default: range: depends on the length of the teleportId |
| :------ | :------ |

#### Returns

| [`RoomInfo`](../interfaces/mw.RoomInfo.md) | Source information transmitted by players |
| :------ | :------ |

Example usage: Create a script called "ServerScript" and place it in the scene. The code is as follows:
___

### getSourceInfo <Score text="getSourceInfo" /> 

`Static` **getSourceInfo**(`teleportId`): [`RoomInfo`](../interfaces/mw.RoomInfo.md) <Badge type="tip" text="other" />

Obtain the source information of the transmission

#### Parameters

| `teleportId` `string` | Usage: The transmission ID to be queried default: range: depends on the length of the teleportId |
| :------ | :------ |

#### Returns

| [`RoomInfo`](../interfaces/mw.RoomInfo.md) | Source information transmitted by players |
| :------ | :------ |

Example usage: Create a script called "ServerScript" and place it in the scene. The code is as follows:

@Component export default class Server extends Script { protected onStart(): void { // The interface for obtaining transmission source information needs to be initiated on the server side, and using it on the client side will result in an error if (SystemUtil.isServer()) { Player.onPlayerJoin.add((player: Player) => { // Use Player's teleportId property to query source information const sourceInfo = TeleportService.getSourceInfo(player.teleportId); if (sourceInfo) { console.log("Teleport from:"); console.log(GameId: $); console.log(`RoomId: $`{sourceInfo.roomId}); } else { // If it is not the current scene transmitted into, there is no source information console.log("Not join by Teleport.") } }); } } }

ts
___

### getTeleportData <Score text="getTeleportData" /> 

`Static` **getTeleportData**(`teleportId`): [`TeleportData`](../modules/Core.mw.md#teleportdata) <Badge type="tip" text="other" />

Retrieve the data set in TeleportOptions when calling the transport interface

#### Parameters

| `teleportId` `string` | Usage: Delivery Id to query default: range: determine according to the length of the teleportId |
| :------ | :------ |

#### Returns

| [`TeleportData`](../modules/Core.mw.md#teleportdata) | The data carried during transmission |
| :------ | :------ |

Example usage: Create a script called "ServerScript" and place it in the scene. The code is as follows:
___

### getTeleportData <Score text="getTeleportData" /> 

`Static` **getTeleportData**(`teleportId`): [`TeleportData`](../modules/Core.mw.md#teleportdata) <Badge type="tip" text="other" />

Retrieve the data set in TeleportOptions when calling the transport interface

#### Parameters

| `teleportId` `string` | Usage: Delivery Id to query default: range: determine according to the length of the teleportId |
| :------ | :------ |

#### Returns

| [`TeleportData`](../modules/Core.mw.md#teleportdata) | The data carried during transmission |
| :------ | :------ |

Example usage: Create a script called "ServerScript" and place it in the scene. The code is as follows:

@Component export default class Server extends Script { protected onStart(): void { // The API for acquiring the data carried during transmission needs to be initiated at the server, and will report an error when used at the client if (SystemUtil.isServer()) { Player.onPlayerJoin.add((player: Player) => { // Use the Player's teleportId property to query the data carried during transmission const data = TeleportService.getTeleportData(player.teleportId); if (data) { console.log(Teleport data: $``); } else { // If the current scene is not transmitted, there is no data carried; It could also be that no data was specified during transmission console.log("Not join by Teleport or no data.") } }); } } }

ts