Unity V4 Configuration API Reference for Realtime Apps
Unity V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code
Configuration
Description
PNConfiguration
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
Method(s)
To create configuration
instance you can use the following function in the Unity V4 SDK:
new PNConfiguration();
Properties Type Required Defaults Description SubscribeKey
string Yes SubscribeKey
from Admin Portal.PublishKey
string Optional PublishKey
from Admin Portal (only required if publishing).SecretKey
string Optional SecretKey
(only required for access operations, recommended to be used on secure servers due to security reasons ).CipherKey
string Optional If cipher
is passed, all communications to/from PubNub will be encrypted.UUID
string Yes SDK generated uuid
UUID
to use. You should set a uniqueUUID
to identify the user or the device that connects to PubNub.
Allowing the SDK to generate a randomUUID
can result in significant billing impacts, particularly on an MAU pricing plan.LogVerbosity
PNLogVerbosity Optional PNLogVerbosity.NONE
Set PNLogVerbosity.BODY
to enable debugging. To disable debugging use the optionPNLogVerbosity.NONE
AuthKey
string Optional Not set
If Access Manager is utilized, client will use this authKey
in all restricted requests.Secure
bool Optional true
Use SSL
.MessageQueueOverflowCount
int Optional 100 When the limit is exceeded by the number of messages received in a single subscribe request, a status event PNRequestMessageCountExceededCategory
is fired.SubscribeTimeout
int Optional 310
The subscribe
request timeout.The value is in seconds.NonSubscribeTimeout
int Optional 10
For non subscribe
operations (publish, herenow, etc), how long to wait to connect to PubNub before giving up with a connection timeout error.The value is in seconds.FilterExpression
string Optional Not set
Used to subscribe with a custom filter expression. HeartbeatNotificationOption
PNHeartbeatNotificationOptions Optional PNHeartbeatNotificationOptions.FAILURES
Heartbeat
notifications, by default, the SDK will alert on failed heartbeats (equivalent to:PNHeartbeatNotificationOptions.FAILURES
).
Other options such as all heartbeats (PNHeartbeatNotificationOptions.ALL
) or no heartbeats (PNHeartbeatNotificationOptions.NONE
) are supported.Origin
string Optional Custom origin
if needed.ReconnectionPolicy
PNReconnectionPolicy Optional PNReconnectionPolicy.NONE
Set to PNReconnectionPolicy.LINEAR
for automatic reconnects. Use optionPNReconnectionPolicy.NONE
to disable automatic reconnects.Use optionPNReconnectionPolicy.EXPONENTIAL
to set exponential retry interval.PresenceTimeout
int Optional 0
Use to set custom presence server timeout.The value is in seconds. PresenceInterval
int Optional 0
Used to set custom interval to send the ping back to the server. This is automatically set to a recommended value when PresenceTimeout is set to a custom value.The value is in seconds. MaximumReconnectionRetries
int Optional infinity
Sets how many times to retry to reconnect before giving up. SuppressLeaveEvents
bool Optional When true
the SDK doesn't send out the leave requests.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
// get subscribeKey from Admin Portal
pnConfiguration.SubscribeKey = "SubscribeKey";// required
// publishKey from Admin Portal (only required if publishing)
pnConfiguration.PublishKey = "PublishKey";
// secretKey (only required for access and history delete operations , keep away from Android/iOS)
pnConfiguration.SecretKey = "SecretKey";
// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
pnConfiguration.CipherKey = "CipherKey";
// UUID to be used as a device identifier, a default UUID is generated
// if not passed
pnConfiguration.UUID = "PubNubUnityExample";
// Enable Debugging
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
// if Access Manager is utilized, client will use this authKey in all restricted requests
pnConfiguration.AuthKey = "authKey";
// use SSL.
pnConfiguration.Secure = true;
// PSV2 feature to subscribe with a custom filter expression
pnConfiguration.FilterExpression = "such=wow";
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
pnConfiguration.HeartbeatNotificationOption = PNHeartbeatNotificationOption.All
pnConfiguration.PresenceTimeout = 60;
pubnub = new PubNub(pnConfiguration);
Initialization
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 -> General -> 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;
Description
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as PublishKey
and SubscribeKey
.
Method(s)
To Initialize
PubNub you can use the following method(s) in the Unity V4 SDK:
new PubNub(pnConfiguration);
Parameter Type Required Description pnConfiguration
PNConfiguration Yes Goto Configuration for more details.
Basic Usage
Initialize the PubNub client API:
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.Secure = true;
pnConfiguration.UUID = "myUniqueUUID";
pubnub = new PubNub(pnConfiguration);
Returns
It returns the PubNub instance for invoking PubNub APIs like Publish()
, Subscribe()
, History()
, HereNow()
, etc.
Other Examples
Initialize a non-secure client:
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.Secure = true; pnConfiguration.UUID = "myUniqueUUID"; pubnub = new PubNub(pnConfiguration);
Initialization for a Read-Only client:
In the case where a client will only read messages and never publish to a channel, you can simply omit the
PublishKey
when initializing the client:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; pubnub = new PubNub(pnConfiguration);
-
Set a custom
UUID
to identify your users.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "mySubscribeKey"; pnConfiguration.PublishKey = "myPublishKey"; pnConfiguration.Secure = true; pnConfiguration.UUID = "myUniqueUUID"; pubnub = new PubNub(pnConfiguration);
Initializing with SSL Enabled:
This examples demonstrates how to enable PubNub Transport Layer Encryption with
SSL
. Just initialize the client withSecure
set totrue
. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.Secure = true; pnConfiguration.UUID = "myUniqueUUID"; pubnub = new PubNub(pnConfiguration);
- Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Anyone with the
SecretKey
can grant and revoke permissions to your app. Never let yourSecretKey
be discovered, and to only exchange it / deliver it securely. Only use theSecretKey
on secure server-side platforms.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.For applications that will administer PAM permissions, the API is initialized with the
SecretKey
as in the following example:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.SubscribeKey = "my_subkey"; pnConfiguration.PublishKey = "my_pubkey"; pnConfiguration.SecretKey = "my_secretkey"; pnConfiguration.UUID = "myUniqueUUID"; pnConfiguration.Secure = true; pubnub = new PubNub(pnConfiguration);
Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the
SecretKey
to sign all PAM messages to the PubNub Network.
Event Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding Listeners
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:
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("SubscribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
}
if (mea.SignalEventResult != null) {
Debug.Log ("SubscribeCallback in SignalEventResult" + mea.SignalEventResult.Channel + mea.SignalEventResult.Payload);
}
if (mea.UserEventResult != null) {
Debug.Log(mea.UserEventResult.Name);
Debug.Log(mea.UserEventResult.Email);
Debug.Log(mea.UserEventResult.ExternalID);
Debug.Log(mea.UserEventResult.ProfileURL);
Debug.Log(mea.UserEventResult.UserID);
Debug.Log(mea.UserEventResult.ETag);
Debug.Log(mea.UserEventResult.ObjectsEvent);
}
if (mea.SpaceEventResult != null) {
Debug.Log(mea.SpaceEventResult.Name);
Debug.Log(mea.SpaceEventResult.Description);
Debug.Log(mea.SpaceEventResult.SpaceID);
Debug.Log(mea.SpaceEventResult.ETag);
Debug.Log(mea.SpaceEventResult.ObjectsEvent);
}
if (mea.MembershipEventResult != null) {
Debug.Log(mea.MembershipEventResult.UserID);
Debug.Log(mea.MembershipEventResult.Description);
Debug.Log(mea.MembershipEventResult.SpaceID);
Debug.Log(mea.MembershipEventResult.ObjectsEvent);
}
if (mea.MessageActionsEventResult != null) {
Debug.Log(mea.MessageActionsEventResult.Channel);
if(mea.MessageActionsEventResult.Data!=null){
Debug.Log(mea.MessageActionsEventResult.Data.ActionTimetoken);
Debug.Log(mea.MessageActionsEventResult.Data.ActionType);
Debug.Log(mea.MessageActionsEventResult.Data.ActionValue);
Debug.Log(mea.MessageActionsEventResult.Data.MessageTimetoken);
Debug.Log(mea.MessageActionsEventResult.Data.UUID);
}
Debug.Log(mea.MessageActionsEventResult.MessageActionsEvent);
Debug.Log(mea.MessageActionsEventResult.Subscription);
}
}
Removing Listeners
pubnub.SubscribeCallback -= SubscribeCallbackHandler;
Handling Disconnects
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:
pubnub.Reconnect();
break;
}
}
if (mea.MessageResult != null) {
Debug.Log("SubscribeCallback in message" + mea.MessageResult.Channel + mea.MessageResult.Payload);
}
if (mea.PresenceEventResult != null) {
Debug.Log("SubscribeCallback in presence" + mea.PresenceEventResult.Channel + mea.PresenceEventResult.Occupancy + mea.PresenceEventResult.Event);
}
}
Listener status events
Category | Description |
---|---|
PNNetworkIssuesCategory | A subscribe event experienced connection issues when running. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAcknowledgmentCategory | Used API reported success with this status category. |
PNAccessDeniedCategory | Request 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. |
PNTimeoutCategory | Used API didn't receive a response from server in time. |
PNDisconnectedCategory | Client unsubscribed from specified real-time data channels. |
PNUnexpectedDisconnectCategory | Subscribe loop failed and at this moment client is disconnected from real-time data channels. This could due to the machine or device is not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy. |
PNBadRequestCategory | Request cannot be completed as not all required values have been passed (like subscribe key , publish key ) or passed values are of unexpected data type. |
PNMalformedFilterExpressionCategory | Subscription request cannot be processed as the passed filter expression is malformed and cannot be evaluated. |
PNMalformedResponseCategory | Request received in response non-JSON data. It can be because of an error message from the proxy server (if applicable). |
PNDecryptionErrorCategory | History API may return this status category in case if some messages can't be decrypted. |
PNTLSConnectionFailedCategory | TLS handshake issues. In most cases is because of poor network quality and packets loss and delays. |
PNRequestMessageCountExceededCategory | This status event will be fired each time the client receives more messages than the value of RequestMessageCountThreshold, set in PNConfiguration . |
PNReconnectionAttemptsExhausted | In case of network disconnect the PubNub client SDK will attempt to reconnect a finite number of times after which this status is sent and the re-connection attempts will stop. |
PNUnknownCategory | PubNub SDK returns this error for SDK exceptions or when server responds with an error. |
UUID
Description
These functions are used to set/get a user ID on the fly.
Method(s)
To set/get UUID
you can use the following method(s) in Unity V4 SDK:
UUID
Property Type Required Description UUID
string Yes Uuid
to be used as a device identifier, a defaultUuid
is generated if not passed.pnConfiguration.UUID;
A property in the PNConfiguration class.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.UUID = "myUniqueUUID";
pubnub = new PubNub(pnConfiguration);
string UUID = pnConfiguration.UUID;
Authentication Key
Description
Setter and getter for users auth key.
Method(s)
AuthKey
Parameter Type Required Description AuthKey
string Yes If Access Manager is utilized, client will use this AuthKey
in all restricted requests.pnConfiguration.AuthKey;
A property in the PNConfiguration class.
Basic Usage
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.AuthKey = "authKey";
pubnub = new PubNub(pnConfiguration);
string AuthKey = pnConfiguration.AuthKey;
Returns
Get Auth key
returns the current authentication key
.
Filter Expression
Requires Stream Controller add-on Requires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.
To set/get filters you can use the following property. To learn more about filtering, refer to the Publish Messages documentation.
Property(s)
FilterExpression
Property Type Required Description FilterExpression
string Yes PSV2 feature to Subscribe
with a custom filter expression.pnConfiguration.FilterExpression;
A property in the PNConfiguration class.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.FilterExpression = "such=wow";
pubnub = new PubNub(pnConfiguration);
string FilterExpression = pnConfiguration.FilterExpression;