Skip to content
ChatService

Service / ChatService

ChatService Class

Chat service

The voice chat function needs to be activated on the mobile end, and pie has no effect. It can be tested using a mobile device.

Table of contents

Accessors

onVoiceStatusChange(): MulticastDelegate<(userId: string, lastVolume: number, currentVolume: number, isOpenAudio: boolean) => void> other
Voice chat commission, callback for each voice call
voiceChatEnabled(): boolean other
Obtain whether the function is neither able to listen nor speak, false is no, neither able to listen nor speak; True means it can be heard or spoken.

Methods

asyncBroadcastMessage(type: MessageType, content: string): Promise<BroadcastMessageResult> other
Send a rich text message to the chat window, and prohibit call the API in the callback.
asyncCloseMic(): Promise<boolean> other
Turn off your own voice.
asyncCollapseChatWindow(isCollapsed: boolean): Promise<boolean> other
Whether to open or fold the chat box in the game. True is open; False is collapse.
asyncEnableChatWindow(isEnabled: boolean): Promise<boolean> other
Turn on or off the chat function of a client. True is open; False is closed.
asyncMuteAll(): Promise<boolean> other
One click to block all Player 'voices.
asyncMutePlayer(userId: string): Promise<boolean> other
Block the voice of the specified Player.
asyncOpenMic(): Promise<boolean> other
Open your own voice.
asyncSendMessage(content: string): Promise<BroadcastMessageResult> other
Send a shortcut message with the sender's name automatically included. It is consistent with the language entered in the chat box. Rich text is not supported.
asyncUnmuteAll(): Promise<boolean> other
Open all players' voice with one click.
asyncUnmutePlayer(userId: string): Promise<boolean> other
Open the voice of the designated player.
asyncsetUserCanChat(userId: string, canChat: boolean): Promise<boolean> other
Set specified user chat permissions
getUserCanChat(userId: string): Promise<boolean> other
Obtain chat permissions for designated users

Accessors

onVoiceStatusChange

Static get onVoiceStatusChange(): MulticastDelegate<(userId: string, lastVolume: number, currentVolume: number, isOpenAudio: boolean) => void> other

Voice chat commission, callback for each voice call

Returns

MulticastDelegate<(userId: string, lastVolume: number, currentVolume: number, isOpenAudio: boolean) => void>Has the player's voice been successfully set.

voiceChatEnabled

Static get voiceChatEnabled(): boolean other

Static set voiceChatEnabled(voice): void other

Obtain whether the function is neither able to listen nor speak, false is no, neither able to listen nor speak; True means it can be heard or spoken.

note: The API can take effect only when the voice function is enabled

Returns

booleanHas the player's voice been successfully set.

Set the function of neither listening nor speaking, false is no, neither listening nor speaking; True means it can be heard or spoken.

note: The API can take effect only when the voice function is enabled

Parameters

voice booleanEnable or disable
default: true

Has the player's voice been successfully set.

Methods

asyncBroadcastMessage

Static asyncBroadcastMessage(type, content): Promise<BroadcastMessageResult> other

Send a rich text message to the chat window, and prohibit call the API in the callback.

Parameters

type MessageTypeUsage: Type of message sent
content stringUsage: Message content range: Less than 1200 string lengths

Returns

Promise<BroadcastMessageResult>The result of sending a message

Limit the maximum number of messages sent within 60 seconds from the first message sent. After clearing the timer, the next message sent will start counting again.

note: Enable the chat box chat function for the interface to take effect


asyncCloseMic

Static asyncCloseMic(): Promise<boolean> other

Turn off your own voice.

Returns

Promise<boolean>Is the voice setting successful.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncCloseMic().then(()=>{console.log("asyncCloseMic")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncCloseMic().then(()=>{console.log("asyncCloseMic")});
     }
 }

asyncCollapseChatWindow

Static asyncCollapseChatWindow(isCollapsed): Promise<boolean> other

Whether to open or fold the chat box in the game. True is open; False is collapse.

Parameters

isCollapsed booleanUsage: Folding box open close Boolean parameter

Returns

Promise<boolean>Return whether the folding was successfully opened.

Example usage: Create a script called "ChatExample", place it in the object manager, open the script, enter the following code to save, run the game, this effect can only be tested on the mobile end, the code is as follows:

ts
@Component
 export default class ChatExample extends Script {

     protected onStart(): void {
          ChatService.asyncCollapseChatWindow(true);
     }
 }
@Component
 export default class ChatExample extends Script {

     protected onStart(): void {
          ChatService.asyncCollapseChatWindow(true);
     }
 }

asyncEnableChatWindow

Static asyncEnableChatWindow(isEnabled): Promise<boolean> other

Turn on or off the chat function of a client. True is open; False is closed.

Parameters

isEnabled booleanUsage: Enable or disable Boolean parameters for chat function

Returns

Promise<boolean>Whether the chat function is successfully turned on or off.

Example usage: Create a script called "ChatExample", place it in the object manager, open the script, enter the following code to save, run the game, this effect can only be tested on the mobile end, the code is as follows:

ts
@Component
 export default class ChatExample extends Script {

     protected onStart(): void {
          ChatService.asyncEnableChatWindow(true);
     }
 }
@Component
 export default class ChatExample extends Script {

     protected onStart(): void {
          ChatService.asyncEnableChatWindow(true);
     }
 }

asyncMuteAll

Static asyncMuteAll(): Promise<boolean> other

One click to block all Player 'voices.

Returns

Promise<boolean>Has the player's voice been successfully set.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncMuteAll().then(()=>{console.log("asyncMuteAll")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncMuteAll().then(()=>{console.log("asyncMuteAll")});
     }
 }

asyncMutePlayer

Static asyncMutePlayer(userId): Promise<boolean> other

Block the voice of the specified Player.

Parameters

userId stringPlayer's userid
default: null range: depends on the length of userId

Returns

Promise<boolean>Has the player's voice been successfully set.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncMutePlayer(Player.localPlayer.userId).then(()=>{console.log("asyncMutePlayer")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncMutePlayer(Player.localPlayer.userId).then(()=>{console.log("asyncMutePlayer")});
     }
 }

asyncOpenMic

Static asyncOpenMic(): Promise<boolean> other

Open your own voice.

Returns

Promise<boolean>Is the voice setting successful.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncOpenMic().then(()=>{console.log("asyncOpenMic")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncOpenMic().then(()=>{console.log("asyncOpenMic")});
     }
 }

asyncSendMessage

Static asyncSendMessage(content): Promise<BroadcastMessageResult> other

Send a shortcut message with the sender's name automatically included. It is consistent with the language entered in the chat box. Rich text is not supported.

Parameters

content stringUsage: message content range: less than 128 string lengths

Returns

Promise<BroadcastMessageResult>The result of sending a message

note: Enable the chat box chat function for the interface to take effect

Usage example: create a script named "messageExample", place it in the object manager, open the script, enter the following code to save it, run the game. The code is as follows:

ts
@Component
export default class NewExample extends Script {

    protected onStart(): void {
        if (SystemUtil.isClient()){
            this.test();
        }
        if(SystemUtil.isServer()){
            Event.addClientListener("bro_two",()=>{
                ChatService.asyncBroadcastMessage(MessageType.Room,"bro").then(()=>{
                    console.log("asyncBroadcastMessage is called");
                });
            });
        }

        if(SystemUtil.isClient()){
            Event.addLocalListener("bro",()=>{
                Event.dispatchToServer("bro_two");
            });
        }
    }

    private async test(): Promise<void> {
        let btn = new ButtonUI();
        InputUtil.onKeyDown(Keys.F, async () => {
            let playerPos = Player.localPlayer.character.worldTransform.position;
            let result = InputUtil.projectWorldPositionToWidgetPosition(playerPos);
            if (result) {
                btn.button.position = result.screenPosition;
            }
        })
    }

}

class ButtonUI {
    public button: StaleButton;
    public buttonTwo: StaleButton;

    constructor(fun: Function = null) {
        this.creatUI(fun);
    }

    private creatUI(fun: Function = null) {
        // Create a UI object
        let ui = UserWidget.newObject();
        // Add UI to screen
        ui.addToViewport(1);
        // Create a canvas component
        let rootCanvas = Canvas.newObject();
        rootCanvas.size = new Vector2(1920, 1080);
        rootCanvas.position = Vector2.zero;
        // Set Ui's root canvas to rootCanvas
        ui.rootContent = rootCanvas;
        // Create a button
        this.button = StaleButton.newObject(rootCanvas);
        this.button.position = new Vector2(1000, 310);
        this.button.size = new Vector2(200, 50);
        this.button.text = "SendMes";
        this.button.transitionEnable = true;
        this.button.pressedImagColor = LinearColor.red;
        this.button.visibility = SlateVisibility.Visible;
        this.button.onClicked.add(() => {
            console.log("btn ")
            ChatService.asyncSendMessage("hello").then(()=>{
                console.log("asyncSendMessage is called");
            });
            if (fun) {
                fun();
            }
        });
        this.buttonTwo = StaleButton.newObject(rootCanvas);
        this.buttonTwo.position = new Vector2(1700, 310);
        this.buttonTwo.size = new Vector2(150, 50);
        this.buttonTwo.text = "BroMes";
        this.buttonTwo.transitionEnable = true;
        this.buttonTwo.pressedImagColor = LinearColor.red;
        this.buttonTwo.visibility = SlateVisibility.Visible;
        this.buttonTwo.onClicked.add(() => {
            console.log("btn ")
            Event.dispatchToLocal("bro");
            if (fun) {
                fun();
            }
        });

    }
}
@Component
export default class NewExample extends Script {

    protected onStart(): void {
        if (SystemUtil.isClient()){
            this.test();
        }
        if(SystemUtil.isServer()){
            Event.addClientListener("bro_two",()=>{
                ChatService.asyncBroadcastMessage(MessageType.Room,"bro").then(()=>{
                    console.log("asyncBroadcastMessage is called");
                });
            });
        }

        if(SystemUtil.isClient()){
            Event.addLocalListener("bro",()=>{
                Event.dispatchToServer("bro_two");
            });
        }
    }

    private async test(): Promise<void> {
        let btn = new ButtonUI();
        InputUtil.onKeyDown(Keys.F, async () => {
            let playerPos = Player.localPlayer.character.worldTransform.position;
            let result = InputUtil.projectWorldPositionToWidgetPosition(playerPos);
            if (result) {
                btn.button.position = result.screenPosition;
            }
        })
    }

}

class ButtonUI {
    public button: StaleButton;
    public buttonTwo: StaleButton;

    constructor(fun: Function = null) {
        this.creatUI(fun);
    }

    private creatUI(fun: Function = null) {
        // Create a UI object
        let ui = UserWidget.newObject();
        // Add UI to screen
        ui.addToViewport(1);
        // Create a canvas component
        let rootCanvas = Canvas.newObject();
        rootCanvas.size = new Vector2(1920, 1080);
        rootCanvas.position = Vector2.zero;
        // Set Ui's root canvas to rootCanvas
        ui.rootContent = rootCanvas;
        // Create a button
        this.button = StaleButton.newObject(rootCanvas);
        this.button.position = new Vector2(1000, 310);
        this.button.size = new Vector2(200, 50);
        this.button.text = "SendMes";
        this.button.transitionEnable = true;
        this.button.pressedImagColor = LinearColor.red;
        this.button.visibility = SlateVisibility.Visible;
        this.button.onClicked.add(() => {
            console.log("btn ")
            ChatService.asyncSendMessage("hello").then(()=>{
                console.log("asyncSendMessage is called");
            });
            if (fun) {
                fun();
            }
        });
        this.buttonTwo = StaleButton.newObject(rootCanvas);
        this.buttonTwo.position = new Vector2(1700, 310);
        this.buttonTwo.size = new Vector2(150, 50);
        this.buttonTwo.text = "BroMes";
        this.buttonTwo.transitionEnable = true;
        this.buttonTwo.pressedImagColor = LinearColor.red;
        this.buttonTwo.visibility = SlateVisibility.Visible;
        this.buttonTwo.onClicked.add(() => {
            console.log("btn ")
            Event.dispatchToLocal("bro");
            if (fun) {
                fun();
            }
        });

    }
}

asyncUnmuteAll

Static asyncUnmuteAll(): Promise<boolean> other

Open all players' voice with one click.

Returns

Promise<boolean>Is the voice setting successful.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncUnmuteAll().then(()=>{console.log("asyncUnmuteAll")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncUnmuteAll().then(()=>{console.log("asyncUnmuteAll")});
     }
 }

asyncUnmutePlayer

Static asyncUnmutePlayer(userId): Promise<boolean> other

Open the voice of the designated player.

Parameters

userId stringPlayer's userid
default: null range: depends on the length of userId

Returns

Promise<boolean>Is the voice setting successful.

note: The API can take effect only when the voice function is enabled

Usage example: create a script named "NewScript", place it in the object manager, open the script, enter the following code to save, run the game, block all Player 'voices, and cannot test run in editor mode. The code is as follows:

ts
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncUnmutePlayer(Player.localPlayer.userId).then(()=>{console.log("asyncUnmutePlayer")});
     }
 }
@Component
 export default class NewScript extends Script {

     protected onStart(): void {
         ChatService.asyncUnmutePlayer(Player.localPlayer.userId).then(()=>{console.log("asyncUnmutePlayer")});
     }
 }

asyncsetUserCanChat

Static asyncsetUserCanChat(userId, canChat): Promise<boolean> other

Set specified user chat permissions

Parameters

userId stringUser ID range: determine according to ID length
canChat booleanWhether to enable user chat permissions.

Returns

Promise<boolean>Is the setting successful

getUserCanChat

Static getUserCanChat(userId): Promise<boolean> other

Obtain chat permissions for designated users

Parameters

userId stringUser ID range: Unrestricted

Returns

Promise<boolean>Whether the acquisition was successful or not