Add Social Features to your Unity Game with PubNub

Unity Social Features Social.png

The best way for any game to improve player engagement and retention is to integrate real-time interactivity; this means features like in-game chat, alerts, leaderboards & presence (whether a player is online or offline), but developing these features yourself can be time-consuming and distracting - time you could spend better improving other aspects of your game.

PubNub can help.  We are trusted by multiple customers whose players depend on PubNub daily to make their gaming experience engaging and interactive.

This blog is the first in a series of two posts that describe how to add real-time features to your Unity Game using PubNub.  This first part will discuss messaging and social features.  Part two will discuss item trading, leaderboards, and moderation.

With the recent revamp of our Unity SDK, developers can take advantage of modern development practices to quickly add interactive features to their games, such as:

The PubNub Unity Showcase application, available on GitHub, shows how you could add real-time features to your application, so let’s look at how we implemented some of that functionality.

Interfacing with PubNub

You need to configure the PubNub Unity SDK to connect your application to the PubNub network.  Please refer to the Unity SDK instructions for full details, but as an overview, you will:

  1. Add the Unity package through the Package Manager

  2. Obtain PubNub keys by creating a free account at https://admin.pubnub.com/, signing in, and creating an applicati

    on.  It is essential to enable the features on your keyset that your application needs; for example, if you need to track whether users are online or offline, then enable the `presence` feature.  The Unity Showcase application’s readme file explains the different keyset features used by that app and is a good starting point. 

  3. Provide Unity with the `publish` and `subscribe` keys you obtained in the previous step by creating a `PubNubConfigAss.`  Again, for full details of this step, please see the getting started tutorial.

  4. You are now ready to use the PubNub Unity SDK

Player chat and messaging

Being able to exchange messages with other players is fundamental to any gaming community!  PubNub offers you the flexibility you need to implement the best in-app chat system for your game while also allowing it to scale to any number of players.  

PubNub uses the concept of channels to exchange messages between participants; players publish messages on a channel, and other users subscribe to that channel to receive those messages.

A very simple publish and subscribe example in Unity would look like this:

//  Subscribe to receive messages on ‘myAwesomeChannel’
pubnub.Subscribe<string>().Channels(new List<string> {‘myAwesomeChannel’}).Execute()

//  The listener method to receive a message is covered later
//  Publish a message on the ‘myAwesomeChannel’
pubnub.Publish().Message(‘hello’).Channel(‘myAwesomeChannel’).Execute()

Sending a single message on a single channel is fine, but the channel mechanism is incredibly flexible.  The Unity showcase app uses channels to implement chat features to a variety of different groups such as ‘all,’ ‘friends,’ ‘lobby,’ and direct private messages.

Lobby Chat Example:

You want every member of a lobby to be able to receive all messages sent by any participant, as well as be able to send messages to all players in the lobby.  There are a couple of ways you can go about doing this:

You could create a unique channel for every lobby: ‘lobby1’, ‘lobby2’, etc., and dynamically subscribe to and unsubscribe from that channel whenever a player joins or leaves a lobby, respectively; this can help keep things compartmentalized but can be challenging to administer or moderate, where you need a superuser to have access to all messages in all lobbies.

You can better organize your channels using the wildcard operator so a superuser who needs access to all lobbies can subscribe to `chat.lobby.*` to receive all messages.  

The showcase app takes a very permissive approach to lobby messaging, so all players can access all messages in every lobby and can then filter out any messages intended for them; this makes it easy to implement moderation, but in production, you would restrict who has access to which messages based on your channel hierarchy using the PubNub Access Manager, which is outside of the scope of this document.

void OnJoinedRoom()
{
  //  We have joined a lobby.  Listen for all messages sent
  pubnub.Subscribe<string>().Channels(new List<string> {‘chat.lobby.*’}).Execute()
}

void SendMessage()
{
  // Send message to a lobby
  targetChannel = ‘chat.lobby.’ + currentLobbyId;
  pubnub.Publish().Message(‘hello’).Channel(targetChannel).Execute()
}

void Start()
{
  //  Register a listener for PubNub messages
  pubnub.AddListener(listener);
  listener.onMessage += OnPnMessage;
}

void OnPnMessage(Pubnub pn, PnMessageResult<object> result)
{
  //  Received a message sent on result.Channel (the lobby channel)
  Debug.Log($"Message received: {result.Message} on channel {result.Channel}");
}

Private Messaging

In principle, private messages work very similarly to lobby chat messages; it all depends on how you construct your channels, who subscribes to them, and who has access to them.

The Unity showcase app will construct a private chat channel:

targetChatChannel = $"chat.private.{user1}&{user2}";

Which will create a unique channel that only two users will subscribe to and publish on.  Moderation and message translation are discussed later, but also note that a superuser could subscribe to `chat.private.*` to receive all private messages (with access controlled in production).

Additional Messaging Use Cases

PubNub has the messaging feature set to cater to your game, regardless of your use case.

The Message Persistence API allows you to catch up on messages previously sent to a channel, so players joining mid-way through a conversation have the context or for archival purposes.  A dedicated ‘MessageCounts’ API also returns the number of messages received since a player was last active.

File sharing allows users to exchange more than just text data, with storage in the cloud allowing players to send images or audio as part of their messages.

After sending Messages, many use cases involve adding metadata to those messages, which is adjustable with the Message Reactions API.  Most commonly, you can specify a reaction such as 👍 or 🎉 but also use the API to perform “soft edits” of a message and add message threads.

PubNub supports seamless integration with Apple’s APNS and Google’s FCM through its mobile Push Notifications, encouraging users to return to your game on Android or iOS or keep them updated when the game is in the background.

Emoji

Chat is not the only way to exchange messages; sometimes, a simple emoji will suffice when playing an intense game.

PubNub’s messaging system is not limited to text strings; for example, during a game, if one player wants to send a smiley face 🙂 the other players will need to know who sent the message, what emoji they are sending, and probably some other metadata such as a message ID.

Additionally, you do not need the same guaranteed service of delivery with emoji compared to messaging, so the PubNub Signal API is ideal for this kind of short-lived message with less network overhead

To send an emoji, the Unity showcase code looks as follows:

int[] emojiMsg = new int[3];
emojiMsg[0] = playerID;
emojiMsg[1] = MessageConstants.idMsgEmoji;
emojiMsg[2] = emojiId;

pubnub.Signal().Message(emojiMsg).Channel(currentGameChannel).Execute((result, status) =>
{
  //  Signal was sent
});

The logic to receive PubNub Signals is very similar to how messages are received:

void Start()
{
  //  Register a listener for PubNub messages
  pubnub.AddListener(listener);
  listener.onMessage += OnPnMessage; //  Receive Messages
  listener.onSignal += OnPnSignal; //  Receive Signals
}

Social features

Adding social features to your game is the most effective way to foster an active and emotionally invested player community.

Having a list of friends, knowing when they are on or offline, and allowing profile personalization are all expected features of any multiplayer game but can be challenging to implement at scale - unless you use PubNub.

Our Unity showcase app features a rudimentary friend system, allowing you to add friends, chat with them directly, and see their online presence.

Player Presence

The PubNub Presence API can determine a user’s online presence.  When users subscribe to a channel, they are considered present on that channel, so each channel has its presence indication, and the system is flexible enough to allow you only to register to receive presence changes on specific channels.

Let’s consider how the Unity showcase uses presence:

When a player launches the application, they are automatically subscribed to a ‘global’ channel, which returns a count of the total number of players online.

To subscribe to a channel and declare an event listener to receive presence notifications, you can specify "WithPresence" when subscribing to that channel.

pubnub.Subscribe().Channels(new List {‘global’}).WithPresence().Execute()

And then, to receive updates to the channel’s presence, add a listener:

void Start()
{
  pubnub.AddListener(listener);
  …
  listener.onPresence += OnPnPresence; //  State of presence has changed
}

void OnPnPresence(Pubnub pubnub, PNPresenceEventResult result)
{
  //  The channel this event refers to is given by result.Channel
  //  The presence event will be one of ‘join,’ ‘leave,’ and ‘timeout’ to indicate if a user is online or offline
  //  result.Event will contain the presence event.
}

Note: Another presence event, "state-change", will notify you when the presence state changes and is used by the Unity Showcase to manage the lobbies.

You will also need to determine any online or offline players when you first launch the application, and the HereNow API will return who is currently subscribed to a channel

PNResult herenowResponse = await pubnub.HereNow()
  .Channels(new string[]
  {
    ‘global’
  })
  .IncludeUUIDs(true)
  .ExecuteAsync();

PNHereNowResult hereNowResult = herenowResponse.Result;

//  hereNowResult contains an array of channels, in this case just one, ‘global’, and each channel has occupant data.  Since we specified IncludeUUIDs(true) we will also be told the user IDs who are present, as opposed to just a count of users, and these can be mapped to the data in App Context, discussed later

Friend List

Our Unity showcase app uses a PubNub Channel Group to keep track of your friends as well as their online or offline status.  Channel groups allow developers to bundle thousands of channels into a single group that can be subscribed to but not published to (you need to publish to the individual channels)

By grouping together all the private channels of any user’s friends, the presence of those friends can be retrieved efficiently.  When adding a new friend, their private chat channel is added to the channel group that represents the player’s friends, and we can register to receive presence notifications for that created group.  If you were not using PubNub (or using something other than channel groups), it would be very challenging to determine the online state for multiple users across any number of dynamic friend lists. 

The API call looks very similar to the global presence state described previously, but notice that we are passing a channel group array, not an array of channels.

.ChannelGroups(new string[] {
  _cgFriendList
  })
  .IncludeState(true)
  .IncludeUUIDs(true)
  .ExecuteAsync();

For more details about setting up a friend list and status feed with PubNub, please check out our best practice guide.

Continued in part two…

This blog described adding real-time communication and social features to your Unity application using PubNub.  Part two will cover item trading, real-time leaderboards, and moderation.

PubNub can help you improve your player engagement and retention by quickly integrating real-time features into your game regardless of scale.  Please check out our gaming solution page and Unity developer path to learn more. 

To start building video games with PubNub, you can sign up for a free trial account with no obligation. When you are ready to continue your journey or have questions, our support and devrel teams are here to help.