PubNub Unity SDK v6.0.9

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Unity package

Unity Package can be downloaded from the latest release.

https://github.com/pubnub/unity/releases/download/vv6.0.9/PubNub.unitypackage

Get the source code

https://github.com/pubnub/unity

Configure PubNub

  1. Download the PubNub Unity package

  2. Import the package to your Unity project by going to Assets > Import Package > Custom Package.

  3. Configure your keys:

    using PubNubAPI;
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.SubscribeKey = "my_subkey";
    pnConfiguration.PublishKey = "my_pubkey";
    pnConfiguration.SecretKey = "my_secretkey";
    pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
    pnConfiguration.UserId = "myUniqueUserId";

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

pubnub.SubscribeCallback += SubscribeCallbackHandler;

//Handler
void SubscribeCallbackHandler(object sender, EventArgs e) {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if (mea.Status != null) {
switch (mea.Status.Category) {
case PNStatusCategory.PNUnexpectedDisconnectCategory:
case PNStatusCategory.PNTimeoutCategory:
// handle publish
break;
}
}
if (mea.MessageResult != null) {
show all 60 lines

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

To subscribe, you send a subscribe() call. It is best to define the message before you introduce the listeners and send the subscribe call, so make sure to place the relevant code in the appropriate places in your code.

pubnub.Publish()
.Channel("channel1")
.Message("test message")
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("Publish Timetoken: {0}", result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
pubnub.Subscribe()
.Channels(new List<string>() {
"my_channel"
})
.Execute();

Putting it all together

Here's a simple Hello, World implementation:

using PubNubAPI;
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
pnConfiguration.UserId = "myUniqueUserId";

Dictionary<string, string> message = new Dictionary<string, string>();
message.Add("msg", "Hello, world");

PubNub pubnub = new PubNub(pnConfiguration);

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;
show all 46 lines

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The code you just created does a few things:

  • configures a PubNub connection
  • adds the Status, MessageResult, and PresenceEventResult event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
pnConfiguration.UUID = "myUniqueUUID";

Adding event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added three listeners to your code: MessageResult, PresenceEventResult, and Status. The message listener listens for incoming messages on a particular channel. When it receives a message, the code simply prints the received message. This is why you see "Hello world" displayed in the console.

The presence listener reacts to events connected to presence. In this example, when a new subscriber joins a channel, the information about the channel and its occupancy is printed out to the console.

The most noteworthy of listeners in this example is the status listener that triggers the publishing of the "Hello world" message.

pubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if (mea.Status != null) {
if (mea.Status.Category.Equals(PNStatusCategory.PNConnectedCategory)) {
pubnub.Publish()
.Channel("my_channel")
.Message(message)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
show all 27 lines

For more information, refer to the Listeners section of the SDK documentation.

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named my_channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, and strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When your code successfully connects to a channel, it calls the Publish() method, which sends the "Hello, world" message.

if (mea.Status != null) {
if (mea.Status.Category.Equals(PNStatusCategory.PNConnectedCategory)) {
pubnub.Publish()
.Channel("my_channel")
.Message(message)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
}
}

You can subscribe to more than one channel with a single subscribe call but in this example, you subscribe to a single channel:

pubnub.Subscribe()
.Channels(new List<string>(){
"my_channel"
})
.Execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Next steps

You have just learned how to use the Unity SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation which covers PubNub APIs in more detail.

Last updated on