UnityPubNub Unity V4 SDK v4.0.4

 

These docs are for PubNub 4.x for Unity which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.x for Unity.

If you have questions about the PubNub for Unity SDK, please contact us at support@pubnub.com.





Download the PubNub Unity package and import it to your Unity project by going to Assets -> Import Package -> Custom Package. Now that your PubNub Unity Package has been imported, you must enable it in the Test Runner. To enable the PubNub Unity Package, go to Window -> Test Runner. Click on the mini drop down menu next to the window close button, and click Enable playmode tests for all assemblies. You will have to restart your Unity editor to finalize these changes. Congrats, you are now all setup to start using the PubNub Unity SDK!

(OR if using the code from the source add files from PubNubUnity/Assets folder to the Assets folder of your project.)

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

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

pubnub = new PubNub(pnConfiguration);

pubnub.SusbcribeCallback += (sender, e) => { 
	SusbcribeEventEventArgs mea = e as SusbcribeEventEventArgs;

	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);
					}
				});
		}
	}
	if (mea.MessageResult != null) {
		Debug.Log("In Example, SusbcribeCallback in message" + mea.MessageResult.Channel);
		Dictionary<string, string> msg = mea.MessageResult.Payload as Dictionary<string, string>;
		Debug.Log("msg: " + msg["msg"]);
	}
	if (mea.PresenceEventResult != null) {
		Debug.Log("In Example, SusbcribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
	}
};

pubnub.Subscribe()
	.Channels(new List<string>(){
		"my_channel"
	})
	.Execute();
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

Instantiate a new Pubnub instance. Only the SubscribeKey is mandatory. Also include PublishKey if you intend to publish from this instance, and the SecretKey if you wish to perform PAM administrative operations from this Unity V4 instance.

 

For security reasons you should only include the secret-key on a highly secured server. The secret-key is only required for granting rights using our Access Manager.

When you init with SecretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

 It is recommended that the PubNub instance is instantiated in a static class and reused across the application.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.Secure = false;

pubnub = new PubNub(pnConfiguration);
pubnub.SusbcribeCallback += SusbcribeCallbackHandler;

//Handler
void SusbcribeCallbackHandler(object sender, EventArgs e) {
	SusbcribeEventEventArgs mea = e as SusbcribeEventEventArgs;

	if (mea.Status != null) {
		switch (mea.Status.Category) {
			case PNStatusCategory.PNUnexpectedDisconnectCategory:
			case PNStatusCategory.PNTimeoutCategory:
				pubnub.Publish()
					.Channel("my_channel")
					.Message("Hello from the PubNub Unity SDK")
					.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);
						}
					});
			break;
		}
	}
	if (mea.MessageResult != null) {
		Debug.Log("Channel" + mea.MessageResult.Channel);
		Debug.Log("Payload" + mea.MessageResult.Payload);
		Debug.Log("Publisher Id: " + mea.MessageResult.IssuingClientId);
	}
	if (mea.PresenceEventResult != null) {
		Debug.Log("SusbcribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
	}
}
pubnub.SusbcribeCallback -= SusbcribeCallbackHandler;
void SusbcribeCallbackHandler(object sender, EventArgs e) {
	SusbcribeEventEventArgs mea = e as SusbcribeEventEventArgs;

	if (mea.Status != null) {
		switch (mea.Status.Category) {
			case PNStatusCategory.PNUnexpectedDisconnectCategory:
			case PNStatusCategory.PNTimeoutCategory:
				pubnub.Reconnect();
			break;
		}
	}
	if (mea.MessageResult != null) {
		Debug.Log("SusbcribeCallback in message" + mea.MessageResult.Channel + mea.MessageResult.Payload);
	}
	if (mea.PresenceEventResult != null) {
		Debug.Log("SusbcribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
	}
}
CategoriesDescription
PNNetworkIssuesCategoryA subscribe event experienced connection issues when running.
PNReconnectedCategorySDK was able to reconnect to pubnub.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAcknowledgmentCategoryUsed API reported success with this status category.
PNAccessDeniedCategoryRequest failed because of access error (active PAM). status.AffectedChannels or status.AffectedChannelGroups contain list of channels and/or groups to which user with specified auth key doesn't have access.
PNTimeoutCategoryUsed API didn't receive a response from server in time.
PNDisconnectedCategoryClient unsubscribed from specified real-time data channels.
PNUnexpectedDisconnectCategorySubscribe loop failed and at this moment client is disconnected from real-time data channels.
PNBadRequestCategoryRequest cannot be completed as not all required values have been passed or passed values are of unexpected data type.
PNMalformedFilterExpressionCategorySubscription request cannot be processed as the passed filter expression is malformed and cannot be evaluated.
PNMalformedResponseCategoryRequest received in response non-JSON data. It can be because of an error message from the proxy server (if applicable).
PNDecryptionErrorCategoryHistory API may return this status category in case if some messages can't be decrypted.
PNTLSConnectionFailedCategoryTLS handshake issues. In most cases is because of poor network quality and packets loss and delays.
PNRequestMessageCountExceededCategoryThis status event will be fired each time the client receives more messages than the value of RequestMessageCountThreshold, set in PNConfiguration.
Call Time() to verify the client connectivity to the origin:
pubnub.Time()
	.Async((result, status) => {              
		if (status.Error) {
			Debug.Log(string.Format("Time Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {
			Debug.Log(string.Format("DateTime {0}, In Example, result: {1}", DateTime.UtcNow ,result.TimeToken));
		}
	});
pubnub.Subscribe()
    .Channels(new List<string>() {
        "my_channel"
    })
    .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Publish a message to a channel:
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);
		}
	});
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.HereNow()
	.Channels(new List<string>(){
		"my_channel"
	})
	.ChannelGroups(new List<string>() {
		"my_channel_group"
	})
	.IncludeState(true)
	.IncludeUUIDs(true)
	.Async((result, status) => {
		if (status.Error) {
			Debug.Log(string.Format("HereNow Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {               
			Debug.Log(string.Format("DateTime {0}, In Example, Channels: {1} {2}", DateTime.UtcNow , result.TotalChannels, result.TotalOccupancy));
		}
		Debug.Log(status.Error);
	});
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.Subscribe()
	.Channels(new List<string>() {
		"my_channel"
	})
	.WithPresence()
	.Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.History()
	.Channel("history_channel")
	.Count(100)
	.Async ((result, status) => {                
		if(status.Error){
			Debug.Log (string.Format("History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {
			foreach (PNHistoryItemResult histItem in result.Messages){
				Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
			}
		}
	});
pubnub.Unsubscribe()
	.ChannelGroups(new List<string>(){
		"my_channel_group"
	})
	.Channels(new List<string>() {
		"my_channel"
	})
	.Async((result, status) => {          
		if (status.Error) {
			Debug.Log(string.Format("Unsubscribe Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {
			Debug.Log(string.Format("DateTime {0}, In Unsubscribe, result: {1}", DateTime.UtcNow, result.Message));
		}
	});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

For more details, please see the CleanUp section.

pubnub.CleanUp();