Skip to content

Script Examples

How to Send a Message from UE to a Show UI

You can use the WebSocket API to send messages from Unreal Engine to a Show UI. In this guide, we'll demonstrate how to set up WebSocket communication to subscribe to a channel and receive notifications from the Unreal Engine.

Setting Up the WebSocket Connection

First, start editing a Show UI in UI Builder. Thus, you initialize a WebSocket connection to the Unreal Engine on your Show UI by specifying the server address (localhost:5000 in this case). The WebSocket will allow the Show UI to send and receive messages from the engine.

Handling WebSocket Events

  • onopen Event: This event triggers when the websocket connection is successfully established. Here, we'll subscribe to a channel (e.g., "Brice") to receive notifications.
  • onmessage Event: This event triggers when the Show UI receives a message from UE websocket. We’ll parse the message and handle notifications.
 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
// Initialize a new WebSocket connection to the server at localhost on port 5000
const ws = new WebSocket('http://localhost:5000');
// Function to send messages to Unreal Engine via WebSocket
function send(method: string, url: string, body?: any) {
  // Check if the WebSocket connection is open
  if (ws.readyState !== WebSocket.OPEN) {
    console.log('Not Connected to UE'); // If not open, log a message and exit the function
    return;
  }
  // If connection is open, send the message as a JSON string containing method, URL, and body
  ws.send(JSON.stringify({ method, url, body }));
}
// Event listener for when the WebSocket connection is successfully established
ws.onopen = (e) => {
  console.log('Connected to UE WebSocket'); // Log when connected to the WebSocket
  // Subscribe to a notification channel named "Brice" by sending a POST request
  send('POST', '/api/notification/subscribe', { channel: 'Brice' });
}
// Event listener for when a message is received from UE via WebSocket
ws.onmessage = (e) => {
  // Ensure the received data is a string before processing
  if (typeof(e.data) !== 'string')
    return;
    // Parse the received message as JSON to extract notification data
  const notification = JSON.parse(e.data);
  // Log the received notification details (type and message)
  console.log('Notification received');
  console.log('Type:', notification.type);
  console.log('Message:', notification.message);
}

UESendMessageEventGraph

The console output in UI Builder when reviewing the Show UI will be:

ConsoleMessage

Sending Commands with Keyboard Shortcuts

You can also trigger specific actions within the Show UI using keyboard shortcuts. For example, by pressing Ctrl+Shift+H, you can take a profile action and read the previous playlist entry.

1
2
3
4
KeyboardShortcuts.on('Ctrl+Shift+H', e => {
  Api.profile.takeIn();
  Api.playlist.readPrev();
});