SelectUnity Configuration API Reference for Realtime Apps

These docs are for version 3.7.10 of the Unity SDK. To check out the docs for the latest version Click Here.
 

PubNub 4.x for Unity is our latest and greatest! Please click here for our PubNub 4.x for Unity docs and SDK.

PubNub 3.x for Unity will encounter End Of Life (EOL) Mar 12, 2019. All users currently on 3.x should begin migrating to 4.x. The 3.x SDK will continue to work. We will no longer support it and if you run into an issue, we will request that you upgrade to the latest version before solving the issue.

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

Unity complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.


Add the Scripts and ThirdParty folders from PubNub's Unity repo to your Unity projects Assets folder and then use this
using PubNubMessaging.Core;
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.
To Initialize Pubnub you can use the following method(s) in the Unity SDK:
  1. ParameterTypeRequiredDescription
    publish_keystringYesSpecifies the required publish_key to be used only when publishing messages to a channel. This key can be specified at initialization or along with a publish() and need not be specified if the client will not publish data to any channel.
    subscribe_keystringYesSpecifies the required subscribe_key to be used for subscribing to a channel.
    secretKeystringYesSpecifies the secret key.
    cipherKeystringYesSpecifies the cipher key.
    sslOnboolYesSetting a value of true enables transport layer encryption with SSL/TLS. Default is false.
  2. ParameterTypeRequiredDescription
    publish_keystringYesSpecifies the required publish_key to be used only when publishing messages to a channel. This key can be specified at initialization or along with a publish() and need not be specified if the client will not publish data to any channel.
    subscribe_keystringYesSpecifies the required subscribe_key to be used for subscribing to a channel.
    secretKeystringYesSpecifies the secret key.
  3. ParameterTypeRequiredDescription
    publish_keystringYesSpecifies the required publish_key to be used only when publishing messages to a channel. This key can be specified at initialization or along with a publish() and need not be specified if the client will not publish data to any channel.
    subscribe_keystringYesSpecifies the required subscribe_key to be used for subscribing to a channel.
Pubnub pubnub = new Pubnub(
    "my_pubkey",
    "my_subkey",
    "",
    "",
    true
);
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), history(), here_now(), etc.
  1. Pubnub pubnub = new Pubnub("demo", "demo");
  2. 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:
    pubnub = new Pubnub("", "demo");
  3. Set a custom UUID to identify your users.
    Pubnub pubnub = new Pubnub( "my_pubkey", "my_subkey");
    pubnub.SessionUUID ="Stephen";
    
  4. It is possible to define custom logging and actions through the use of callbacks:
    Pubnub pubnub = new Pubnub("demo", "demo");
    pubnub.Subscribe<string>(
       "my_channel",
        DisplaySubscribeReturnMessage,
        DisplaySubscribeConnectStatusMessage,
        DisplayErrorMessage
    );
    void DisplaySubscribeReturnMessage(string result) {
        UnityEngine.Debug.Log("SUBSCRIBE REGULAR CALLBACK:"); 
        UnityEngine.Debug.Log(result);
        if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
                {
                    List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
                    if (deserializedMessage != null && deserializedMessage.Count > 0)
                    {
                        object subscribedObject = (object)deserializedMessage[0];
                        if (subscribedObject != null)
                        {
                            //IF CUSTOM OBJECT IS EXCEPTED, YOU CAN CAST THIS OBJECT TO YOUR CUSTOM CLASS TYPE
                            string resultActualMessage = pubnub.JsonPluggableLibrary.SerializeToJsonString(subscribedObject);
                       }
                    }
                }
    }
    void DisplaySubscribeConnectStatusMessage(string result)
    {
        UnityEngine.Debug.Log("SUBSCRIBE CONNECT CALLBACK");
    }
    void DisplayErrorMessage(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  5. This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with sslOn set to true. 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.

    Pubnub pubnub = new Pubnub(
        "my_pubkey",
        "my_subkey",
        "",
        "",
        true
    );
  6. Requires Access Manager add-on XRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
     

    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secret key be discovered, and to only exchange it / deliver it securely. Only use the secretKey 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:
    Pubnub pubnub = new Pubnub("", "my_subkey", "my_secretkey");
    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.
This function is used to set a user ID on the fly.
To set UUID you can use the following method(s) in Unity SDK:
  1. This property accepts a string
pubnub.SessionUUID = pubnub.GenerateGuid().ToString();
  1. String channel = pubnub.GenerateGuid().ToString();
    
    pubnub.Subscribe<string>(
       "channel",
        DisplaySubscribeReturnMessage,
        DisplaySubscribeConnectStatusMessage,
        DisplayErrorMessage
    );
    void DisplaySubscribeReturnMessage(string result) {
        UnityEngine.Debug.Log("SUBSCRIBE REGULAR CALLBACK:"); 
        UnityEngine.Debug.Log(result);
        if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
                {
                    List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
                    if (deserializedMessage != null && deserializedMessage.Count > 0)
                    {
                        object subscribedObject = (object)deserializedMessage[0];
                        if (subscribedObject != null)
                        {
                            //IF CUSTOM OBJECT IS EXCEPTED, YOU CAN CAST THIS OBJECT TO YOUR CUSTOM CLASS TYPE
                            string resultActualMessage = pubnub.JsonPluggableLibrary.SerializeToJsonString(subscribedObject);
                       }
                    }
                }
    }
    void DisplaySubscribeConnectStatusMessage(string result)
    {
        UnityEngine.Debug.Log("SUBSCRIBE CONNECT CALLBACK");
    }
    void DisplayErrorMessage(PubnubClientError pubnubError) {
        UnityEngine.Debug.Log(pubnubError.StatusCode);
    }
  2. Pubnub pubnub = new Pubnub( "my_pubkey", "my_subkey");
    pubnub.SessionUUID = pubnub.GenerateGuid.ToString();
    
    
  3. String uuid = pubnub.GenerateGuid().ToString();
Setter and getter for users auth key.
  1. Property NameTypeRequiredDescription
    AuthenticationKeystringYesAuthentication Key
  2. The property returns the auth key.
pubnub.AuthenticationKey = "my_new_authkey";
pubnub.AuthenticationKey
pubnub.AuthenticationKey = "";
Get Auth key returns the current authentication key.
This default value is set to true, which means the last received time token will be used to retry subscribe and presence thus retrieving the messages missed during the disconnect. If the variable is set to false, retry subscribe and presence will use timetoken = 0.
Property NameTypeDescription
EnableResumeOnReconnectboolDefault = true
Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
To set/get filters you can use the following methods.
  1. The property accepts a string.
  2. The property returns a string

pubnub.FilterExpression = "region=='east'";
pubnub.FilterExpression;
Heartbeat Settings
  1. Property NameTypeDescription
    LocalClientHeartbeatIntervalintThis variable sets the time interval(heart-beat) to check internet/network/tcp connection for HTTP requests when an active request is initiated. In the example, we check network/tcp connection every 15 seconds. It is also used for re-connect interval when overrideTcpKeepAlive = true (for Mono framework 2.10.9). Re-connect applies only for subscribe and presence.

    Default = 15
    PresenceHeartbeatintThis variable is to set the heartbeat for the subscribed channel for presence before expiry.

    Default = 63
    PresenceHeartbeatIntervalintThis variable is to set the heartbeat interval for the subscribed channel for presence before expiry.

    Default = 60
Logging Settings
  1. Property NameTypeDescription
    PubnubErrorLevelPubnubErrorFilter.LevelThis variable is used to filter out error messages that go to Error Callback. Other available options are Warning, Critical

    Default = PubnubErrorFilter.Level.Info
    PubnubLogLevelLoggingMethod.LevelThis variable is used to log any trace/error message that occur in the application. Other available log level options are LoggingMethod.Level.Error, LoggingMethod.Level.Info, LoggingMethod.Level.Verbose and LoggingMethod.Level.Warning. This variable is for troubleshooting purposes only.

    Default value = LoggingMethod.Level.Info
Timeout Settings
  1. Property NameTypeDescription
    NonSubscribeTimeoutintThis variable sets the time limit in seconds for the web request to run. Applies to regular operation requests like time, publish, here now and detailed history. In the example, we terminate HTTP requests after 15 seconds of not hearing back from the server.

    Default = 15
    SubscribeTimeoutintThis variable sets the time limit in seconds for the web request to run. Applies to subscribe and presence web requests. In the example, we terminate HTTP requests after 310 seconds of not hearing back from the server.

    Default = 310
PubNub Other Settings
  1. Property NameTypeDescription
    EnableJsonEncodingForPublishboolIt should be set to false when you are going to Publish a JSON serialized string. By default it is set to true and the SDK takes care of JSON serializing the message for you.

    Default = true
    NetworkCheckMaxRetriesintThis variable is to set the maximum number of re-tries for re-connect to check internet/network connection for subscribe and presence. In the example, we attempt 50 times to check connection.

    Default = 50
    NetworkCheckRetryIntervalintThis variable is to set the wait time for re-subscribe and re-presence, if the previous subscribe or presence fail. This variable is valid only when overrideTcpKeepAlive = false If there is no internet/network connection after pubnubNetworkCheckRetries attempts for subscribe, "Unsubscribed after 50 failed retries" message will be sent and unsubscribe occurs automatically. Similary for presence, "Presence-unsubscribed after 50 failed retries"

    For publish, here_now, detailed history and time, there is no attempt to re-connect. If the request fails due to http web request timeout, Operation timeout error be sent. If there is network/internet disconnect, error message "Network connect error" will be sent.

    Default = 10
    OriginstringOrigin is a public property used to set PubNub origin.

    Default = ps.pndsn.com

Go to Publish & Subscribe