How to Add Real-time Chat to Your Unity Game
Real-time chat or in-game chat increases player engagement and aids user retention. Real-time chat allows players to communicate with each other, fostering a sense of community and providing a platform for social interaction that makes a more enjoyable gaming experience.
Incorporating real-time chat is easier said than done. To start from scratch, it takes a lot of resources to build, maintain, and scale when your player count increases. Luckily, PubNub has made it easier than ever to inject real-time functionalities into Unity games with our real-time, low-latency API platform. Whether you're developing for Windows, Mac, iOS, Android, Virtual Reality systems such as Oculus and Meta Quest, or going cross-platform, our Unity SDK has you covered.
Continue reading to learn how to add real-time chat to your Unity video game with PubNub, starting from understanding how to set up different channel patterns, learning how to send/receive messages, and then enhance/secure your in-game chat with other features such as moderation, emojis, reactions, and GIFs.
Getting Started with PubNub
Before you begin to understand how to set up your in-game chat, you’ll need to understand the PubNub platform and how to configure your application to take advantage of the platform’s features.
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 will subscribe to the PubNub network and parse the message. The message can contain anything you’d like, as long as it’s under 32 KB (and preferably in JSON).
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, listening for an assortment of messages.
While you need to specify the exact channel name when you publish a message, you can subscribe to multiple channels at once via multiplexing, which is subscribing to one or more channels by providing the channel names as an array of strings.
Why is this information necessary? Your entire in-game messaging system will be based on the concept of channels: how you format and secure your channel pattern name determines what type of chat you want.
Install and Configure the PubNub Unity SDK
To begin, you'll need to configure the PubNub Unity SDK to connect your application to the PubNub network. Please refer to the Unity SDK documentation for full details, but as an overview, you will need to:
- Add the Unity package through the Package Manager.
- Create a free PubNub account and obtain your PubNub Keys. It is essential to enable the features on your keyset that your application needs - for the essential Pub/Sub functionality, you'll simply need Stream Controller enabled. We'll be sure to cover any other settings you might need to configure for advanced features.
- Provide Unity with the publish and subscribe keys you obtained in the previous step to configure the PubNub GameObject. You should also provide a UserId, as every PubNub object requires a unique identifier to establish a connection to PubNub. Once you have done so, initialize the PubNub object:
- Add event listeners for your game to react to events and messages. There are different event listeners to be able to implement custom logic to respond to each type of message or event, but for the core functionality of exchanging chat messages, you’ll simply need the Message Event listener (You’ll learn how to add additional features to your real-time chat to make it more engaging later on in this guide):
Before you can start publishing to send messages to other devices and subscribing to receive messages from the publishers, you’ll need to define what your channel name will be. Remember: how you format your channel pattern determines what type of chat you want to implement.
Defining Different Chat Patterns
You’ll need to consider what types of chat you’ll need to implement for your game. This section is meant to discuss the pattern the channel should follow, not the entire setup for obtaining the required information from your game or users. If you would like to see the different chat patterns in a Unity project that uses PubNub, check out our Unity Showcase Game.
All or Global Chat allows for communication between all players in a game. You can set up a general chat by publishing and subscribing to messages with a common channel that all players are subscribed to. You can set up the channel structure for global players:
Each client would then subscribe to the channel and will ensure everyone receives the same messages in real time, creating a shared chat experience that everyone can be a part of.
Private or Whisper Chat allows players to have one-on-one conversations, where only the two players involved can chat with each other and nobody else. In a Private or Whisper Chat channel pattern, you would have each user subscribe to a channel structure intended for private conversations:
This uses the concept of Wildcard Subscribe. This feature can be used to subscribe to a hierarchical list of channels, where you can subscribe to lots of channels with a single name declaration.
For instance, when a user is about to send a message privately to another user, you would then concatenate the current PubNub User ID (or UUID/uuid), which represents the unique identifier that identifies the user in the PubNub network and the User ID of the intended recipient of the message. While you can always get the User ID for the current user (via pubnub.GetCurrentUserId()), you’ll need to obtain the intended recipient’s User ID. Once you have the recipient’s User ID, you can concatenate the channel such as:
Since you specify a wildcard channel pattern like chat.private.*, your app will subscribe to all channel names that match that pattern. This ensures that you don’t need to always know the channel name at runtime. Finally, using the User IDs ensures that the channel name will be unique and that the conversation stays between the two users.
Creating a Friend or Buddy chat allows players to privately communicate with specific players with whom they want to form a closer connection, whether they are newly met players or friends outside of the game.
In a Friend/Buddy Chat pattern, you’ll need to create a channel pattern that is unique to each device or player, similar to how you would construct the private chat channel pattern by appending your User ID:
You would then repeat this for every user you would to be friends with - you would replace their User IDs in the chanFriendChat string with that of pubnub.GetCurrentUserId(). While you now have the channel pattern in place, you can’t simply subscribe using a wildcard pattern such as chat.friends.*; instead, you’ll need a mechanism to determine which players are friends.
A solution for this problem is PubNub’s Channel Groups, which allows you to manage a large number of channels at once. Channel Groups are essentially a pointer to a list of channels; in this case, the Channel Group is unique to the player and will contain a reference to all of the player’s friends:
Note: Channel Group names follow the same conventions as channel names, but they cannot contain periods in their name, hence the difference in pattern structure.
Similar to how you subscribe to Channels with the pubnub object (explained in the next section), you can also subscribe to Channel Groups at the same time. This means that since the player is subscribed to their friend Channel Group, each time a new friend is added, that friend’s chanFriendChat is added to the player’s Friend Channel Group and will receive messages in the Message event listener whenever any of those channels publishes a message. While you can’t publish to a Channel Group, you can simply publish a message to any of the affiliated channels within the channel group and every subscriber (friend) would receive that message.
Using the Channel Groups API for the PubNub Unity SDK, you can add, list, and remove friends/channels from Channel Groups that you have authorization to do so. The Channel Groups feature is also used for determining when Friends also come online/offline, known as Presence. This will be discussed in detail in our detailed How-To Add a Friend List in Unity guide.
In games featuring guilds, alliances, or clans, a dedicated chat environment can greatly benefit team coordination and camaraderie. This style of group chat enables communication among multiple users, promoting collaboration and teamwork amongst a larger number of players than just your friends. A Guild/Alliance/Clan Chat allows members of the same group to plan strategies, share achievements, or simply bond to form a more personal community within the game.
To set this up with PubNub is the same concept as implementing Friend/Buddy Chat. You would construct Channel Groups for each type, subscribe to these Channel Groups, and add friends to these Channel Groups when authorized. Any messages published to a channel associated with these Channel Groups will trigger the event listener and you can display the chat appropriately.
Channel Groups are a great way to manage large groups, as each player’s Channel Group can manage 2000 channels (in this case players), which is more than enough for even the largest guilds in massive online games. Better yet, every individual client connected to the PubNub network can have 10 Channel Groups, meaning you have access to subscribing to 20,000 channels if necessary.
Party or Lobby chats cater to small, temporary groups formed for a particular game session or mission. While these styles of chat are intended for different purposes, their implementation is similar to the pattern of creating a private/whisper chat channel pattern.
First, create a base string for each of the types of group chat. When you subscribe to your array of channels (discussed in the next step), you’ll subscribe using a wildcard subscribe to listen for all requests:
When the lobby or party is formed, a player is designated as the leader or owner of the group, whether they initiated the group or if determined based on their internet connection and region. These types of players are called party leaders or hosts. You would then concatenate the host player’s User ID with a base string, creating a unique channel pattern. Any new player who is invited to join the party or lobby will subscribe to these channels dynamically, effectively having them join the group. The channel can then be deleted once the party or lobby has been finished or disbanded.
Putting it All Together
Once you have determined which chat types you would like to implement into your game based on the channel pattern, it’s time to send and receive messages in real time by publishing and subscribing to these channels.
The process begins with crafting the message payload. This could be a simple text chat or more complex data structures, depending on the requirements of your Unity game. Once the payload is ready, it's time to publish the message.
The Publish API is used to send a message to all subscribers of the specified chat channel. Although you can only publish to one channel at a time, publishing is performed asynchronously, so it won't block the rest of your code from executing (although you still can publish synchronously if you would like).
For example, if you would like to send a chat message to the party, you would make the following call to not only publish but determine if the PubNub call was successfully made (and handle when the call failed):
Subscribe to Messages
When messages are being published, we need to subscribe to the appropriate channels to receive any incoming messages and events. You can subscribe to multiple chat channels and channel groups with one call:
The player is now connected to the PubNub network and the event listeners wait for an event to occur – in this case, the arrival of a new message – and then execute the code associated with that event.
When a message arrives, the listener triggers a callback, executing the code you've written to handle incoming messages. This could be as simple as displaying the message in a chat room, or something more complex, like triggering in-game events based on chat messages.
Advanced Features to Make In-Game Chat Engaging
Nice work - you have successfully implemented in-game chat to your Unity game for players to send and receive messages in real time! While this already creates a space for players to engage with one another, the functionality implemented is simply the tip of the iceberg - there are a lot of features that you should consider implementing that make in-game chats more engaging for your players.
Load Message History: Message Persistence
In a game, players might need to revisit previous conversations or catch up on missed chats. This is where Message Persistence comes in, enabling the history of chat messages to be saved and retrieved. Implementing the Message Persistence API in your Unity game allows you to store and retrieve chat messages, message actions, and files when needed:
We also provide the flexibility to control how long messages are stored, allowing you to manage storage based on the specific needs and resources of your game. To be able to make use of Message Persistence, you’ll need to enable the feature in the Admin Portal for your keys. You can learn more about this feature in-depth as well as how to enable this feature by following our Message Persistence how-to guide.
Notify Players of Missed Messages: Mobile Push Notifications
With mobile games, players can often be in and out of the app and may miss crucial messages from their team or updates from the game. This is where Mobile Push Notifications come into play. They provide a way to inform players about missed chat messages, game updates, or other important notifications, even when they're not actively in the game.
With the Mobile Push Notifications API, we provide a unified API to send push notifications to both iOS and Android devices. This simplifies the process and allows you to send a single API call to notify all devices, regardless of platform. You can also customize your push notifications, such as sending personalized notifications to individual gamers or broadcasting a message to all players. This flexibility allows you to effectively communicate with your players, keeping them engaged and informed.
To be able to utilize Mobile Push Notifications with PubNub, you’ll need to enable Mobile Push Notifications by following our how-to guide in the Admin Portal. We also have more specific, detailed guides for FCM and APNs Mobile Push Notifications.
More than Just Words: Emojis
Emojis serve as a universal language of emotions in digital communication. They allow players to express their feelings and reactions in a fun and colorful way, making the chat more interactive and engaging.
With PubNub, you can easily implement emoji support in your Unity game by having players publish Signals, rather than messages. Signals are intended for sending small bits of data, as it is much faster and cheaper to send than messages. Since emojis are typically very small in terms of data size, it’s a perfect way to quickly send the data.
You can use PubNub’s Signals API to publish Emojis to a specified chat. For example, if a player wanted to send a waving emoji to the global chat, the following code would be executed when they press send:
Intended recipient players will receive the signal if they are subscribed to the specified channel. In this case, since it is for the global channel, everyone would receive the emoji. To be able to listen for signals, subscribe to the listener event:
You’ll need to make sure that the value of the emoji represents an actual emoji that is defined in Unity. These emojis can be stored and retrieved in the PubNub network via App Context (previously known as Objects) so that any emojis that the player has access to can be retrieved from serverless storage. You can learn more about implementing App Context in your Unity game through our how-to guide.
Respond to Messages: Message Reactions
Message Reactions, such as likes, hearts, thumbs up, stickers, or custom game-specific reactions, provide a quick and easy way for players to respond to chat messages. They not only add interactivity to the chat but also foster a sense of community by allowing players to acknowledge and engage with each other’s messages.
You can use PubNub's Message Actions API to build features like reactions and read receipts, or to associate custom metadata to messages. Similar to how chat applications such as Discord have different reactions and emojis for different servers, so too could your different chat types. You can retrieve the available message reactions for the specified chat channel using the following call when the chat loads:
When a player is about to respond to a message with a reaction, you can do so by adding a Message Reaction to a published message:
PubNub uses time tokens to track precisely when a message has been published in the network. When you receive messages, the time taken is also included in the payload. You would then be able to provide the appropriate time token value in the MessageTimetoken() argument to be able to react to the message.
To be able to listen for the reaction and notify the player who sent the original message, you would need to add a listener and handle the reaction in the OnPNMessageAction method:
Similar to emojis, you can use App Context to retrieve and store how these reactions are visually represented in your game. To be able to make use of Message Reactions, you’ll need to ensure that Message Persistence is enabled for your keys in the Admin Portal.
GIFs and Other Multimedia
Another important feature that enhances the chat experience is sharing multimedia files. Whether it's sharing GIFs, screenshots of funny moments, or even sharing game resources, file sharing brings another level of interaction to your game.
Implementing these types of Multimedia files uses the PubNub File Sharing API. With this functionality, players can upload, download, and delete files they have access to. To be able to send a file, you would make the following call:
For subscribers to listen for the file, you would need to add the event listener and handle how to display the file in the OnPNFile method:
You can also obtain, list information, and delete any of the files associated with different chat channels. You will need to ensure you enable the File Sharing feature in the Admin Portal, as well as Message Persistence. You can learn more about how to do this in our Enabling Files how-to guide.
Secure Your Chat Channels: Access Manager
In any gaming environment, ensuring the security of chat channels is paramount. Whether it's shielding players from unwanted messages or protecting sensitive strategic discussions, your Unity game's chat system needs to be designed with security in mind.
This is where PubNub's Access Manager comes in. It provides a robust and flexible framework for securing your chat channels. With Access Manager, you can control who can publish or subscribe to each of your channels, adding an extra layer of security to your Unity game's chat system.
Access Manager allows you to grant permissions at the user level, channel level, or even at the level of individual keys. You can specify whether a user can read, write, or manage a channel, and these permissions can be dynamically updated as your game's needs change. For example, in a private chat between two players, you can grant only those two players the read and write permissions for their private channel. Similarly, in a guild chat, you can give read and write permissions to all guild members, while granting manage permissions only to the guild leader.
Access Manager also supports token-based authentication, allowing you to securely authenticate users and grant them the appropriate permissions. This ensures that only authorized players can access your game's chat channels, protecting your game community from potential threats.
You’ll need to ensure that you enable Access Manager in the Admin Portal to be able to utilize this feature. You can learn more about how to do this by following this support page on enabling this add-on feature.
In this how-to guide, you’ve learned how to add a robust real-time chat system to your Unity game. We've discussed everything from how to initialize a PubNub object in your environment, to setting up a chat pattern that represents different chat types, and then sending and receiving messages. You even learned how to implement advanced features like emojis, message reactions, and file sharing, as well as the important aspects of any good chat system with message persistence, mobile push notifications, and channel security.
Whether you're an indie developer working on your first game or a seasoned developer looking to enhance your multiplayer game, PubNub's real-time functionality can serve as the infrastructure to support your in-game chat, so you can focus on what matters most.
Learn more with the following resources:
- Read our Unity documentation to learn everything you need to know about adding real-time chat to your game.
- Understand how-to add a Friend List with our Unity guide.
- Learn how our Unity Showcase Game utilizes chat patterns to manage chat rooms and more.
- Dive into the Unity SDK source code.
Feel free to reach out to the Developer Relations Team at email@example.com for any questions or concerns.