Add Real-Time Features in Unreal Engine 5.3 with PubNub

pubnubdevrel

PubNub Developer Relations

Posted on March 8, 2024

Add Real-Time Features in Unreal Engine 5.3 with PubNub

If you're looking to add real-time features to your Unreal Engine (UE) 5.3 multiplayer or online game, you're in the right place. PubNub ensures low-latency messaging and scalability, enhancing player experiences with social features like in-game chat, online status detection, friend lists, scoring systems and leaderboards, and more, all in real time. Whether you're developing for Windows, Mac, iOS, Android, Virtual Reality systems such as Oculus and Meta Quest, or going cross-platform, we take care of the infrastructure layer of your game for real-time interactivity so that you can focus on your application.

Continue reading to see how you can use PubNub’s Unreal Engine Module to implement these real-time features and more into your own UE game.

Please keep in mind that our Unreal Engine Plugin is still early in development, so we would love any feedback sent to devrel@pubnub.com or by submitting a pull request/issue to our GitHub repository.

Prerequisites

Before we get started, you’ll need to get a few things ready:

  1. Unreal Engine: Make sure you have Unreal Engine installed. This post was created using UE 5.3.

  2. IDE: It’s recommended to use Visual Studios with UE. Be sure to follow Epic Games’s instructions on setting up UE 5.3 with Visual Studios.

  3. PubNub: Sign up for a free PubNub Account to get your API keys required to connect to the network. You’ll need to create your app and keyset; you can learn how to do so by following this guide. You’ll also need to enable Presence for online detection and can learn how to do so by reading our how-to guide.

Integrate the PubNub Unreal Module

To be able to use the PubNub Unreal Engine Module to power online features, you’ll need to perform some SDK setup and add it to your project to be able to integrate the features.

SDK Setup

First, clone the SDK repository into your Unreal Engine project source:

git clone [Repository_URL] [Your_Unreal_Project]/Source/ThirdParty/
Enter fullscreen mode Exit fullscreen mode

Replace [Repository_URL] with the actual URL of the PubNub C-Core SDK repository. If the ThirdParty folder does not exist, create it.

If you are on Windows, open the project in Visual Studios. You’ll need access to Tools > Command Line > Developer Command Prompt to execute the nmake command.

Navigate to the SDK directory and compile using the appropriate command for your system (Note: This blog was written using a Windows OS and used the Windows command):

POSIX (Linux/Mac)

Replace option, architecture, and implementation accordingly.

make -C <option> -f <architecture>.mk pubnub_<implementation>.a
Enter fullscreen mode Exit fullscreen mode

Windows:

nmake -f windows.mk
Enter fullscreen mode Exit fullscreen mode

Windows Universal Platform:

nmake -f windows/uwp.mk
Enter fullscreen mode Exit fullscreen mode

OpenSSL:

make -C openssl -f posix.mk pubnub_sync.a
Enter fullscreen mode Exit fullscreen mode

Note: If using the OpenSSL option, ensure your OpenSSL library headers match the Unreal ones.

Open /Source/ThirdParty/PubNubModule/PubNubModule.Build.cs and adjust the Option, Architecture, and Implementation options with the same values you used for compilation. For Example:

private readonly string Option = "windows"; // posix, windows, openssl
private readonly string Architecture = "windows"; // posix, windows
private readonly string Implementation = "callback"; // sync, callback
Enter fullscreen mode Exit fullscreen mode

Import the Module by modifying the project target files to include the PubNub module. Be sure to replace UnrealProject with your actual project name:

public class <UnrealProject>[Editor]Target : TargetRules
{
    public <UnrealProject>[Editor]Target (TargetInfo Target) : base(Target)
    {
        //...
        ExtraModuleNames.Add("PubNubModule");
    }
}
Enter fullscreen mode Exit fullscreen mode

In UnrealProject.uproject:

{
  //...
  "Modules": [
    //...
    {
      "Name": "PubNubModule",
      "Type": "Runtime",
      "LoadingPhase": "Default"
    }
  ],
  //...
}
Enter fullscreen mode Exit fullscreen mode

You’re nearly done with the setup for the SDK - all that is left is to generate the Visual Studios Project files (or refresh the files to include the new changes). You can do so in several ways, including through the Unreal Engine 5.3 Editor, or by right-clicking on the .uproject file in file explorer and generating the Visual Studio project files:

Using the Module

To begin using the PubNub Unreal Engine Module, you’ll need to modify the Module.Build.cs file in the module where you want to use PubNub and add the Module. Be sure to replace Module with the name of your module:

public class <Module> : ModuleRules
{
    public <Module>(ReadOnlyTargetRules Target) : base(Target)
    {
        //...
        PrivateDependencyModuleNames.Add("PubNubModule");
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, you’ll need to include the PubNub header in your files via #include "PubNub.h". You won’t need to wrap the include THIRD_PARTY_INCLUDES_START and THIRD_PARTY_INCLUDES_END as it’s already taken care of.

Implementing Real-Time Features

You’re now ready to begin implementing these real-time use cases into your UE Game! But first, let’s dive a little deeper into understanding how PubNub works at a high level.

PubNub Overview

PubNub is based on the Pub/Sub (Publish/Subscribe) model. A user will publish a message, which is essentially a payload that contains all relevant information, to the PubNub network. Users who want to receive or listen to the message and other generated events will subscribe to the PubNub network and parse the message. Event listeners are used to catch messages and events generated in the PubNub Network and trigger based on an action taken place.

To ensure the message gets to the right recipients, channels are used as the mechanism through which the data is transmitted from one device to another. Channels are required each time a device wants to publish and subscribe to the PubNub network. While a user can only publish one message at a time, a user can subscribe to many different channels at a time.

In-Game Chat

In-game chat or in-app messaging increases player engagement and aids user retention. In-game chat allows gamers to communicate with each other, fostering a sense of community and providing a platform for social interaction that makes a more enjoyable user experience.

You can add in-game chat to your UE 5 video game for real-time communication by making use of PubNub’s Pub/Sub architecture by publishing messages whenever a player sends a message. You would have clients subscribe to the appropriate channels to listen for these messages (where the type of chat is determined by its channel name), catching them in an OnMessageReceived event listener and handling appropriately:

// Initialize the PubNub client
PubNubClient->Init(YourPublishKey, YourSubscribeKey);

// Sending a message
FString Channel = "all-chat";
FString Message = "Hello, fellow friends!";
PubNubClient->Publish(Channel, Message);

// Receiving messages:
PubNubClient->Subscribe(Channel);
PubNubClient->OnMessageReceived.AddLambda([](const FString& Channel, const FString& Message) {
    // Handle the received message here and display on screen.
    UE_LOG(LogTemp, Warning, TEXT("Received message on %s: %s"), *Channel, *Message);
});
Enter fullscreen mode Exit fullscreen mode

Online Status Detection

Presence is used to determine the online status of your players in your game, generating events to deliver information for their status in real time. Presence is an incredibly important feature for your game, as it lets your players know the online status of their friends, whether they are online/offline, currently in a match or lobby, their location in the game world, and even what activity they are engaged in.

Using the Presence API, you can track when users come and go online, including custom events with User State. You would then subscribe each client to a channel to track presence and listen to these events via the OnPresenceEventReceived event listener:

// Subscribe to a presence channel
FString PresenceChannel = "presence.all";
PubNubClient->Subscribe(PresenceChannel);

// Listen for presence events
PubNubClient->OnPresenceEventReceived.AddLambda([](const FPubNubPresenceEvent& Event) {
    if (Event.Action == EPubNubPresenceAction::Join) {
        UE_LOG(LogTemp, Warning, TEXT("%s joined the game!"), *Event.UUID);
    } else if (Event.Action == EPubNubPresenceAction::Leave) {
        UE_LOG(LogTemp, Warning, TEXT("%s left the game."), *Event.UUID);
    }
    // Handle other presence actions as needed, including custom user state.
});
Enter fullscreen mode Exit fullscreen mode

Friend/Guild/Alliance/Clan Lists

Incorporating a friend, guild. alliance, and clan list in your Unreal Engine game is a key aspect of promoting player engagement. It allows your players to create a closer connection with other players in-game, whether they are friends outside of the game or if they formed a close bond during an intense match.

These lists can be implemented in your game by making use of creating and subscribing to Channel Groups. Channel Groups allow you to manage a large, persistent number of channels at once. Channel Groups are essentially a pointer to a list of channels that allow you to send a single subscribe call for up to 2000 channels per Channel Group. Channel Groups are unique to the User ID that is connected to the network, meaning you can name a channel group uniquely and be tied to that player.

You can add friend/guild/alliance/clan lists by using the Channel Groups API to define each list with a unique name, where adding and removing channels to each list represents relevant players being added/removed from the lists in-game. Both online status detection and chat for these groups would follow the previous sections for in-game chat and online status detection with Presence. You can learn more implementation details about implementing friend/guild/alliance/clan lists by following our documentation on architecture setup.

Live Leaderboards and Scoring Systems

Scoring systems and leaderboards are key aspects of providing a fun gaming experience. Scoring systems provide vital information while players are engaged in an intense match and are necessary to determine the best chance of winning, while leaderboards are used as a way to encourage competition amongst players to view high scores after matches. Both encourage replayability and are an easy way to help player stickiness.

Scoring systems can be implemented similarly to in-game messaging: set up a channel pattern so only those who are in the match receive the updates and subscribe to that channel when the relevant players join the match. Once there are updates to send, such as when new damage updates occur, publish the update by constructing a message and sending it. Check out our scoring systems guide on the different types of scoreboards you can implement for your Unreal Engine project.

Once a match is finished, a final call is made to update the global leaderboards for other players to view. By making use of Functions, you can create and execute business logic on the edge to route, filter, transform, augment, and aggregate real-time messages as they route through the PubNub network. This means that you can host your own code or third-party integrations without spinning up your server to intercept PubNub messages before or after they occur, as well as store relevant information using the KV store module, which is a persistent key-value store that acts as a database for your Functions.

For leaderboards, you want to update the scores after players have finished a match and then notify the players of the updated leaderboard by subscribing to a channel dedicated to leaderboard updates. You can learn more about Functions in detail by diving into our documentation.

What’s Next

In this post, you’ve learned how to add real-time features to your Unreal Engine 5.3 game with PubNub. Whether you want to add in-game messaging, live scoring systems and leaderboards, or even friend/guild/alliance/clan lists, game developers can depend on PubNub to power these features in real time.

If you would like to start adding real-time features to your own UE 5.3 Game with our Unreal Engine Module, be sure to check out the documentation to learn what you need to successfully implement these real-time features. We also have SDKs for other game engines, such as our Unity which is used in our Unity Game to showcase these features discussed in this post and more. And remember, our Unreal Engine Plugin is still early in development, so we would love any feedback or questions sent to devrel@pubnub.com or by submitting a pull request/issue to our GitHub repository.

Contents

PrerequisitesIntegrate the PubNub Unreal ModuleSDK SetupUsing the ModuleImplementing Real-Time FeaturesPubNub OverviewIn-Game ChatOnline Status DetectionFriend/Guild/Alliance/Clan ListsLive Leaderboards and Scoring SystemsWhat’s Next

How can PubNub help you?

This article was originally published on PubNub.com

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub

Check out Live Tour to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup

Sign up for a PubNub account for immediate access to PubNub keys for free

Get Started

The PubNub docs will get you up and running, regardless of your use case or SDK

💖 💪 🙅 🚩
pubnubdevrel
PubNub Developer Relations

Posted on March 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related