Gaming

How to Add Presence to Your Unity Game

How to Add Presence to Your Unity Game

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.

While this feature is vital in game development, incorporating Presence 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. We take care of the infrastructure layer of your apps so that you can focus on your application. 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 Presence to your Unity video game with PubNub, starting from understanding how to configure the PubNub GameObject, how to send/receive messages, and the different features Presence can be used for so players can have a better understanding of the status of their friends and players alike.

Getting Started with PubNub

Before you begin to understand how to set up online status detection with Presence, you’ll need to understand the PubNub platform and how to configure your application to take advantage of the platform’s features.

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.

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. Channels are used in Presence to trigger Presence Events that are sent to event listeners when a user comes online or goes offline, so you’ll need to consider what channels you need that make sense for your game.

Install and Configure the PubNub Unity SDK

To begin, you'll need to install any PubNub dependencies and configure the PubNub Unity SDK to connect your application to the PubNub network. This guide already assumes you have the Unity Game Engine, Unity Assets, and code editors such as Visual Studio installed. Please refer to the Unity SDK documentation for full details, but as an overview, you will need to:

  1. Add the Unity package through the Package Manager.
  2. Create a free PubNub account and obtain your PubNub Keys. You’ll need to enable the features on your keyset that your application needs. For this guide, you’ll need to enable Presence with the default settings. You can learn more in our How to Enable Presence guide.
  3. Create a new Unity Project or open your existing game and provide Unity with the publish and subscribe keys you obtained in the previous step to configure the PubNub GameObject in the Unity Editor. 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:
1 2 3 4 using PubnubApi; using PubnubApi.Unity; … PubNub pubnub = new Pubnub(pnConfiguration);
  1. Add an event listener for your game to react to Presence Events, where your back end will be essentially receiving notifications about when players come online and go offline. There are different event listeners to be able to implement custom logic to respond to each type of message or event, but for this guide, you’ll simply need the Presence Event Listener:
1 2 3 4 5 6 7 8 9 var listener = new SubscribeCallbackListener(); pubnub.AddListener(listener); listener.onPresence += OnPnPresence; … private void OnPnPresence(Pubnub pn, PNPresenceEventResult result) { // The current number of players in the channel’s triggered Presence event Debug.Log(result.Occupancy); }

Subscribing & Presence

Once you’ve finished configuring your PubNub GameObject, you can determine how many players are actively online, as well as listen for when players come online and go offline.

Determine Initial Player Count

You can obtain information about how many players are currently active when your players first log into the game by using the HereNow service:

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 31 32 33 34 35 36 37 38 39 PNResult<PNHereNowResult> herenowResponse = await pubnub.HereNow() .Channels(new string[] { globalPlayerCount, }) .IncludeUUIDs(true) .ExecuteAsync(); PNHereNowResult herenowResult = herenowResponse.Result; PNStatus status = herenowResponse.Status; if (status.Error) { // handle error approproately return; } if (herenowResult != null && herenowResult.Channels != null && herenowResult.Channels.Count > 0) { foreach (KeyValuePair<string, PNHereNowChannelData> kvp in herenowResult.Channels) { PNHereNowChannelData channelData = kvp.Value; Debug.Log("---"); Debug.Log("channel:" + channelData.ChannelName); Debug.Log("occupancy:" + channelData.Occupancy); Debug.Log("Occupants:"); if (channelData.Occupants != null && channelData.Occupants.Count > 0) { for (int index = 0; index < channelData.Occupants.Count; index++) { PNHereNowOccupantData occupant = channelData.Occupants[index]; Debug.Log(string.Format("uuid: {0}", occupant.Uuid)); Debug.Log(string.Format("state:{0}", (occupant.State != null) ? pubnub.JsonPluggableLibrary.SerializeToJsonString(occupant.State) : "")); } } } }

HereNow returns a PNHereNowChannelData object that contains relevant information, including the User IDs of all currently active players in the specified channels you provide, as well as the count of these active players.

Listen for Events

Once you’ve determined the current online status of all active players when you first load the game, you’ll need to listen for Presence Events via the Presence Event Listener that we set up earlier to catch when players join and leave the game.

To do this, you’ll need to first subscribe to the channels you want for the player to connect to the PubNub platform. PubNub will then trigger presence (and other) events as users come online or go offline from the application. For instance, if you want to track the total player count and display it on the main menu of your game, consider having a string globalPlayerCount = “global” and ensure that every player subscribes to this channel. If you want to track when friends come online, consider using Channel Groups to manage a large group of channels and subscribing to that channel group to only receive events that are relevant for that player.

Regardless of how many channels or channel groups you would like to subscribe to, you need to ensure you enable the withPresence parameter when you subscribe with your PubNub GameObject:

1 2 3 4 5 pubnub.Subscribe<string>() .Channels(new string[] {globalPlayerCount}) .ChannelGroups(new string[] {myFriendGroup"}) .WithPresence() .Execute();

When you enable the withPresence parameter, the SDK automatically creates additional presence equivalents of all channels and subscribes to them. These channels are sibling channels where Presence Events are published by PubNub. This is because Presence Events generate many transactions as one would imagine and is useful to separate Presence Events into their channel to manage. These presence channels are named after the main ones but contain an additional -pnpres suffix.

You can directly subscribe to the Presence channel equivalent instead of calling withPresence for specific channels by appending -pnpres at the end of the channel name:

1 2 3 4 pubnub.Subscribe<string>() .Channels(new string[] {“globalPlayerCount-pnpres”}) .ChannelGroups(new string[] {myFriendGroup"}) .Execute();

In this call, Presence Events are generated and caught by the listener for the globalPlayerCount-pnpres channel, while Non-Presence Events such as Message Events are triggered for the myFriendGroup channel group.

Regardless of how you decide to subscribe to generate Presence Events, once a player subscribes using one of these methods, a Presence Event is generated. There are five main types of presence events:

  • join: Fires when a user subscribes to a channel.
  • leave: Fires when a user unsubscribes from a channel (when unsubscribe is called, closes the game, or the connection is terminated).
  • timeout: Fires when a connection to a channel is lost and the subscriber hasn't been seen in 300 seconds.
  • state-change: Fires anytime the user's state is changed. More on state in the next section
  • interval: Fires in interval mode to provide an occupancy count and optionally include delta changes. You can learn more about interval mode and delta changes in the documentation.

Once you receive the event in the Presence Event Listener, you’ll need to check the type of the event and handle it appropriately.

Implement Custom Player Status and Location: Presence State

Nice work - you have successfully implemented Presence in your Unity game for players to be able to obtain the initial online player count, as well as listen for Presence events when players come online when they subscribe to the PubNub network via the Presence Event Listener. While this is already is a powerful feature that is both easy to implement and scalable, online games should be able to provide more specific information to players about where their friends' exact online status is while in the game - are they in a lobby, playing a match, browsing their collectibles, or clearing a dungeon with a group?

To remedy this issue, you can implement a dynamic custom state using Presence State for your players on one or more channels and store this information on a channel as long as that player stays subscribed. This means that as long as they are online, you can update and retrieve their custom state at any point, which is perfect for displaying this information for other players. The events generated when you are retrieving or setting their custom state will be caught by the same Presence Event Listener we set up earlier. Just make sure to check that the event is of type state-change.

You can use the Presence State API for the Unity SDK to get the Presence State of another player by supplying the specific player’s User ID and channels:

1 2 3 4 5 6 7 8 9 10 11 PNResult<NGetStateResult> getstateResponse = await pubnub.GetPresenceState() .Channels(new string[] { "ch-user-a" }) .Uuid("user-a") // uuid of user to fetch .ExecuteAsync(); PNGetStateResult getstateResult = getstateResponse.Result; PNStatus status = getstateResponse.Status; //Update UI based on response

In this call, we are obtaining the custom state of user-a for the channel ch-user-a that can be used to track this specific player’s current status within the game. Although the example is extremely simplified, being able to obtain the custom state of friends and other players within the game is extremely powerful.

To be able to change a player’s state once they transition to a new activity or location, you can call the SetPresenceState operation:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Dictionary<string, object> myState = new Dictionary<string, object>(); myState.Add("current_activity”, “loot_box_opening”); PNResult<PNSetStateResult> setstateResponse = await pubnub.SetPresenceState() .Channels(new string[] { "ch-user-a” }) .UUID(“user-a”) .State(myState) .ExecuteAsync(); PNSetStateResult setstateResult = setstateResponse.Result; PNStatus status = setstateResponse.Status; // handle set state response

With the SetPresenceState() operation, we are setting the custom state of user-a once they transition to performing a new activity, such as opening loot boxes. Since the State passed contains keys that are type object, you can elect to set custom metadata outside of just location and status to be accessible by other players. However, keep in mind that Presence State is only available to be retrieved for players that are actively online and connected to the PubNub network. To store custom metadata about players that you would like to persist, such as profile information and settings, you will want to use the App Context API.

What’s Next

In this how-to guide, you’ve learned how to add Presence to your Unity game to track the online and custom status of players in your game. We've discussed everything from how to initialize a PubNub object in your environment, to subscribing to channels to receive Presence Events and even retrieving/setting custom statuses for your players to manage their specific location/activity in your game.

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.
  • Learn how to add a friend list into your Unity game that utilizes Presence to track when players’ friends come online.
  • Understand how our Unity Showcase Game utilizes Presence to manage total player count, when players’ friends come online, and manage player lobbies.
  • Dive into the Unity SDK source code.

Feel free to reach out to the Developer Relations Team at devrel@pubnub.com for any questions or concerns.