---
source_url: https://www.pubnub.com/docs/sdks/unity/api-reference/configuration
title: Configuration API for Unity SDK
updated_at: 2026-06-04T11:13:14.206Z
sdk_name: PubNub Unity SDK
sdk_version: v9.3.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Configuration API for Unity SDK

PubNub Unity SDK, use the latest version: v9.3.0

Complete API reference for building real-time applications on PubNub with the Unity Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.

Even though you can configure and initialize the Unity SDK directly from Unity Editor via assets, you can also do it programmatically.

Refer to [Getting Started](https://www.pubnub.com/docs/sdks/unity) for instructions on how to set up the Unity SDK using assets.

## Build platform configuration

Different Unity build platforms may require specific configuration to ensure the PubNub SDK functions correctly.

### Mobile build configuration

When building for Android or iOS platforms, you might encounter an issue where the PubNub Unity SDK works perfectly in the Unity Editor but fails to receive messages when deployed to mobile devices. This is typically caused by Unity's code stripping optimization removing PubNub SDK assemblies during the build process.

For detailed solutions to resolve this issue, refer to the [Troubleshooting](https://www.pubnub.com/docs/sdks/unity/troubleshoot) document.

### WebGL configuration

The PubNub Unity SDK is compatible with Unity WebGL builds. To configure your project to build for WebGL:

:::warning Enable Web GL build mode only for builds
Using `UnityWebGLHttpClientService` outside of WebGL builds (including the editor) might cause unexpected behavior due to `UnityWebRequest` being thread-unsafe.
:::

1. In your Unity Editor project tree, right-click any folder and navigate to Create -> PubNub -> PubNub Config Asset. This step creates a new scriptable object where you provide your PubNub account information. Existing Config assetIf you have already created a config asset, you don't have to create a new one.
2. Open the scriptable PNConfigAsset object and mark the Enable Web GL Build Mode checkbox. This sets UnityWebGLHttpClientService as the transport layer in PnManagerBehaviour during initialization. If you don't use PnManagerBehaviour, initialize PubNub with the WebGL build mode using one of the following methods: var pubnub = new Pubnub(pnConfig, httpTransportService: new UnityWebGLHttpClientService(), ipnsdkSource: new UnityPNSDKSource()); var pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfig, webGLBuildMode: true);
3. Go to Edit -> Project Settings -> Player and set Managed Stripping Level to Minimal. Additional HTTP setupIf for some reason you can't turn on the Secure option in either PNConfiguration or the Scriptable Object config file, then you need to also go to Project Settings -> Player -> WebGL Settings and set the Allow downloads over HTTP option to Always allowed.
4. Install the WebGL Threading Patcher. Navigate to Window -> Package Manager, click +, select Add package from git URL, paste the link to the Threading Patcher's GIT repository, and click Add.

These steps configure your project for WebGL builds only. Configure other targets as needed.

## Configuration

A `PNConfiguration` instance stores user-provided settings that control PubNub client behavior.

### Method(s)

As mentioned above, there are two ways to configure your PubNub instance—entirely from the Unity Editor ([described in detail here](https://www.pubnub.com/docs/sdks/unity)) or entirely in code. The first method is faster to set up out of the box, while the second can be easier to integrate into projects less reliant on Unity objects (for example, those using non-MonoBehaviour DI services).

The examples below focus on the pure-code approach.

To create a `PNConfiguration` instance, you can use the following function in the Unity SDK:

```csharp
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
```

| Parameter | Type | Required | Default | 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. |
| UserId | UserId | Yes |  | `UserId` to use. The `UserId` object takes `string` as an argument. You should set a unique identifier for the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the `UserId`, you won't be able to connect to PubNub. |
| LogLevel | PubnubLogLevel | Optional |  | Sets the level of logging detail for this PubNub instance. For more information about enabling logs, refer to the [Logging](https://www.pubnub.com/docs/sdks/unity/logging) document. |
| AuthKey | string | Optional |  | If Access Manager is utilized, client will use this `AuthKey` in all restricted requests. |
| Secure | bool | Optional |  | Use `SSL`. |
| SubscribeTimeout | int | Optional |  | How long to keep the `subscribe` loop running before disconnect. The value is in seconds. |
| NonSubscribeRequestTimeout | int | Optional |  | On `non subscribe` operations, how long to wait for server response. The value is in seconds. |
| FilterExpression | string | Optional |  | Feature to subscribe with a custom filter expression. |
| HeartbeatNotificationOption | PNHeartbeatNotificationOption | Optional |  | `Heartbeat` notifications, by default, the SDK will alert on failed heartbeats (equivalent to: `PNHeartbeatNotificationOption.FAILURES`). Other options such as all heartbeats (`PNHeartbeatNotificationOption.ALL`) or no heartbeats (`PNHeartbeatNotificationOption.NONE`) are supported. |
| Origin | string | Optional |  | Custom `Origin` if needed. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| ReconnectionPolicy | PNReconnectionPolicy | Optional |  | Custom reconnection configuration parameters. Default is `PNReconnectionPolicy.EXPONENTIAL` (subscribe only). Available values: PNReconnectionPolicy.NONE, PNReconnectionPolicy.LINEAR, PNReconnectionPolicy.EXPONENTIAL For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). |
| ConnectionMaxRetries | int | Optional |  | The maximum number of reconnection attempts. If not provided, the SDK will not reconnect. For more information, refer to [Reconnection Policy](https://www.pubnub.com/docs/general/setup/connection-management#reconnection-policy). |
| PresenceTimeout | int | Optional |  | Defines how long the server considers the client alive for presence. This property works similarly to the concept of long polling by sending periodic requests to the PubNub server at a given interval (like every 300 seconds). These requests ensure the client remains active on subscribed channels. If no heartbeat is received within the timeout period, the client is marked inactive, triggering a "timeout" event on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). The value is in seconds. |
| PresenceInterval | int | Optional |  | Specifies how often the client will send heartbeat signals to the server. This property offers more granular control over client activity tracking than `PresenceTimeout`. Configure this property to achieve a shorter presence timeout if needed, with the interval typically recommended to be `(PresenceTimeout / 2) - 1`. |
| Proxy | Proxy | Optional |  | Instruct the SDK to use a `Proxy` configuration when communicating with PubNub servers. |
| EnableTelemetry | bool | Optional |  | Enables the SDK to capture analytics in terms of response time and sends them to PubNub server. It is enabled by default. |
| RequestMessageCountThreshold | Number | Optional |  | `PNRequestMessageCountExceededCategory` is thrown when the number of messages into the payload is above of `requestMessageCountThreshold`. |
| SuppressLeaveEvents | bool | Optional |  | When `true` the SDK doesn't send out the leave requests. |
| DedupOnSubscribe | bool | Optional |  | When `true` duplicates of subscribe messages will be filtered out when devices cross regions. |
| MaximumMessagesCacheSize | int | Optional |  | It is used with `DedupOnSubscribe` to cache message size. Default is `100`. |
| FileMessagePublishRetryLimit | int | Optional |  | The number of tries made in case of Publish File Message failure. Default is `5`. |
| EnableEventEngine | bool | Optional |  | True by default. Whether to use the updated, standardized event processing. For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle.) |
| CryptoModule | AesCbcCryptor(CipherKey) | Optional |  | The cryptography module used for encryption and decryption of messages and files. Takes the `CipherKey` parameter as argument. For more information, refer to the [CryptoModule](#cryptomodule) section. |
| PubnubLog | IPubnubLog | Optional |  | This way of setting a custom logger is deprecated, please use `pubnub.SetLogger(IPubnubLogger)` instead. Pass the instance of a class that implements IPubnubLog to capture logs for troubleshooting. |
| LogVerbosity | PNLogVerbosity | Optional |  | This way of setting this parameter is deprecated, please use `LogLevel` instead. Set PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE |
| CipherKey | string | Optional |  | This way of setting this parameter is deprecated, pass it to `CryptoModule` instead. If cipher is passed, all communications to/from PubNub will be encrypted. |
| UseRandomInitializationVector | bool | Optional |  | This way of setting this parameter is deprecated, pass it to `CryptoModule` instead. When true the IV will be random for all requests and not just file upload. When false the IV will be hardcoded for all requests except File Upload.Default false. |
| Uuid | string | Yes |  | This parameter is deprecated, use `userId` instead. UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub. |

:::warning Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (<`5.0.0`) with existing applications. Never disable random IV on new applications.
:::

#### CryptoModule

`CryptoModule` encrypts and decrypts messages and files. From 7.0.1, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

If you don't set `CryptoModule` but set `CipherKey` and `UseRandomInitializationVector` in config, the client uses legacy encryption.

For configuration details, utilities, and examples, see [Encryption](https://www.pubnub.com/docs/sdks/unity/api-reference/encryption).

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

### Sample code

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```csharp
using System.Collections.Generic;
using PubnubApi;
using PubnubApi.Security.Crypto;
using PubnubApi.Security.Crypto.Cryptors;
using PubnubApi.Unity;
using UnityEngine;

public class PubnubConfigurationExample : MonoBehaviour {
    // Serialized fields to allow configuration within Unity Editor
    [SerializeField] private string userId = "myUniqueUserId";
    [SerializeField] private string subscribeKey = "demo"; // Replace with your actual SubscribeKey
    [SerializeField] private string publishKey = "demo"; // Replace with your actual PublishKey if publishing is needed
    [SerializeField] private string secretKey = "yourSecretKey"; // Used if Access Manager operations are needed
    [SerializeField] private string authKey = "authKey"; // Used if Access Manager is enabled
    [SerializeField] private string filterExpression = "such=wow";
    [SerializeField] private bool useSSL = true;
    [SerializeField] private bool logToUnityConsole = true;

    //Note that you can always use the PnConfigAsset Scriptable Object for setting these values in editor
    [SerializeField] private PNConfigAsset configAsset;

    private void Start() {
        // Initialize a PNConfiguration object with the provided values
        PNConfiguration pnConfiguration = new PNConfiguration(new UserId(userId)) {
            SubscribeKey = subscribeKey,
            PublishKey = publishKey,
            SecretKey = secretKey,
            AuthKey = authKey,
            Secure = useSSL,
            CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") }),
            LogLevel = PubnubLogLevel.All,
            SubscribeTimeout = 310,
            NonSubscribeRequestTimeout = 300,
            FilterExpression = filterExpression,
            HeartbeatNotificationOption = PNHeartbeatNotificationOption.All
        };

        pnConfiguration.SetPresenceTimeoutWithCustomInterval(120, 59);
        pnConfiguration.PresenceTimeout = 120;

        // Create a PubNub instance and perform Unity-specific setup
        Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration, unityLogging: logToUnityConsole);

        // Analogous setup with the Scriptable Object config:
        Pubnub anotherPubnub = PubnubUnityUtils.NewUnityPubnub(configAsset);

        Debug.Log("PubNub configured and ready to use.");
    }
}
```

## Initialization

#### Include the code

```csharp
using PubnubApi;
using PubnubApi.Unity;
```

### Description

This function is used for initializing the PubNub Client API context. You must initialize PubNub before calling any APIs to establish account-level credentials such as `PublishKey` and `SubscribeKey`.

### Method(s)

To `Initialize` PubNub from code you can use the following methods in the Unity SDK:

```csharp
new PubNub(pnConfiguration);
```

| Parameter | Description |
| --- | --- |
| `pnConfiguration` *Type: `PNConfiguration` | Refer to [Configuration](#configuration) for more details. |

```csharp
PubnubUnityUtils.NewUnityPubnub(configuration, webGLBuildMode, unityLogging);
```

| Parameter | Description |
| --- | --- |
| `configuration` *Type: `PNConfiguration` | Refer to [Configuration](#configuration) for more details. |
| `webGLBuildMode`Type: `bool` | Default `false`, if `true` will set the transport layer to be `UnityWebGLHttpClientService` |
| `unityLogging`Type: `bool` | Default `false`, if `true` will set the logger to be `UnityPubNubLogger` |

```csharp
PubnubUnityUtils.NewUnityPubnub(configurationAsset, userId);
```

| Parameter | Description |
| --- | --- |
| `configurationAsset` *Type: `PNConfigAsset` | PubNub configuration Scriptable Object, refer to [Configuration](#configuration) for more details. |
| `userId` *Type: `string` | ID of the user for this `Pubnub` instance |

All three methods return a new `Pubnub` instance.

### Sample code

#### Initialize the PubNub client API

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/
```

### Returns

It returns the PubNub instance for invoking PubNub APIs like `Publish()`, `Subscribe()`, `History()`, `HereNow()`, etc.

### Other examples

#### Initialize a non-secure client

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = false;
Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(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 Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.SubscribeKey = "my_subkey";
Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
```

#### Initializing with SSL enabled

This examples demonstrates how to enable PubNub Transport Layer Encryption with `SSL`. Just initialize the client with `Secure` 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.

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = true;
Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
```

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your 'secretKey'
Anyone with the `SecretKey` can grant and revoke permissions to your app. Never let your `SecretKey` 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 Access Manager permissions, the API is initialized with the `SecretKey` as in the following example:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.Secure = true;

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
```

Now that the PubNub object is instantiated the client can access the Access Manager functions. The PubNub object will use the `SecretKey` to sign all Access Manager messages to the PubNub Network.

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/unity/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/unity/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see [Publish & Subscribe](https://www.pubnub.com/docs/sdks/unity/api-reference/publish-and-subscribe#event-listeners).

## UserId

These functions are used to set/get a user ID on the fly.

### Method(s)

To set a new `UserId` you can use the following method in Unity SDK:

```csharp
pubnub.ChangeUserId(UserId newUserid)
```

| Property | Description |
| --- | --- |
| `newUserid` *Type: `UserId` | The new `UserId` to be used as the Pubnub instance identifier. |

### Sample code

#### Set user ID

```csharp
using PubnubApi;
using PubnubApi.Unity;

pnConfiguration.UserId = new UserId("myUserId");
```

#### Get user ID

```csharp
using PubnubApi;
using PubnubApi.Unity;

UserId currentUserId = pubnub.GetCurrentUserId();
```

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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 or get message filters, you can use the following property. To learn more about filtering, refer to the [Publish Messages](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Property(s)

```csharp
FilterExpression
```

| Property | Description |
| --- | --- |
| `FilterExpression` *Type: string | PSV2 feature to `Subscribe` with a custom filter expression. |

```csharp
pnConfiguration.FilterExpression;
```

A property in the `PNConfiguration` class.

### Sample code

#### Set filter expression

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.FilterExpression = "such=wow";
```

#### Get filter expression

```csharp
using PubnubApi;
using PubnubApi.Unity;

string filterExpression = pnConfiguration.FilterExpression;
```

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.