---
source_url: https://www.pubnub.com/docs/sdks/unity
title: Unity API & SDK Docs v9.3.0
updated_at: 2026-05-18T09:10:22.812Z
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


# Unity API & SDK Docs v9.3.0

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

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your Unity application. PubNub's Unity SDK supports various Unity platforms including:

* Mobile (iOS, Android)
* Desktop (Windows, macOS, Linux)
* WebGL (browser-based games)
* VR/AR (Virtual Reality/Augmented Reality) applications

The core PubNub concepts and API usage remain the same across all these platforms, but initialization may differ slightly depending on your target platform.

:::tip WebGL compatibility
The PubNub Unity SDK is compatible with Unity WebGL builds. For information on how to configure your project for WebGL, refer to [WebGL configuration](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration#webgl-configuration).
:::

## Prerequisites

Before we dive in, make sure you have:

* Unity Editor (2018.4.26f1 or newer)
* Basic understanding of C# and Unity development
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create a new app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

You can install the PubNub Unity SDK in several ways:

#### Install via Package Manager (recommended)

1. Open Unity Editor and navigate to Window -> Package Manager.
2. In the Package Manager window, click + and select Add package from git URL.
3. Paste the PubNub Unity package link and click Add. https://github.com/pubnub/unity.git?path=/PubNubUnity/Assets/PubNub
4. Navigate to PubNub in the editor menu bar and click Set up templates.
5. Restart Unity Editor.

#### Source code

Clone the GitHub repository:

```bash
git clone https://github.com/pubnub/unity.git
```

## Steps

### Configure PubNub

Unity provides a unique way to configure PubNub through the editor interface without writing code:

1. In your project tree, right-click any folder, and navigate to Create -> PubNub -> PubNub Config Asset. This creates a new scriptable object where you provide your PubNub account information.
2. Open the newly created PNConfigAsset scriptable object and provide your publish and subscribe keys. Other configuration items are optional. UserId requirementEvery PubNub client needs a unique identifier. For testing, the Unity SDK can generate a UserId for you, but in production, you should specify your own meaningful UserId to identify clients.
3. In your project tree, right-click a folder, and navigate to Create -> PubNub -> PubNub Manager Script. This creates a script that will handle PubNub operations.
4. Drag the PnManager script onto any game object in your scene. This adds PnManager as a component.
5. Drag the PNConfigAsset onto the PubNub Configuration field inside PnManager (Script).

Alternatively, you can configure PubNub programmatically:

```csharp
// Initialize PubNub using the configuration
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
	SubscribeKey = "demo",
	PublishKey = "demo",
	Secure = true
};

// Create the PubNub instance with the configuration
Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// You can also initializa a "raw" pubnub instance but would have to then setup all Unity-specific functionality by yourself
Pubnub rawPubnub = new Pubnub(pnConfiguration);
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration) section of the SDK documentation.

### Set up 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.

There are two main types of listeners you'll need to set up:

* Status listener - for connection state changes and operational events
* Message listener - for incoming messages

```csharp
// Get the listener from a PNManagerBehaviour:
var listener = pnManagerBehaviour.listener;
// Alternatively, create your own and add it to the Pubnub instance:
var createdListener = new SubscribeCallbackListener();
pubnub.AddListener(createdListener);

// Add callbacks
listener.onStatus += OnPnStatus;
listener.onMessage += OnPnMessage;

// Status event handler
void OnPnStatus(Pubnub pn, PNStatus status) {
	Debug.Log(status.Category == PNStatusCategory.PNConnectedCategory ? "Connected" : "Not connected");
}

// Message event handler
void OnPnMessage(Pubnub pn, PNMessageResult<object> result) {
	Debug.Log($"Message received: {result.Message}");
}
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This is done in three steps:

1. Define a channel to subscribe to.
2. Call `Subscribe()` with the channel name.
3. Set up event listeners to handle incoming messages.

```csharp
// Subscribe to a channel using modern API
Channel channel = pubnub.Channel("TestChannel");
Subscription subscription = channel.Subscription();
subscription.Subscribe<object>();

// Or using the legacy API
pubnub.Subscribe<string>().Channels(new[] { "TestChannel" }).Execute();
```

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/unity/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

```csharp
// Publish a simple message
await pubnub.Publish().Channel("TestChannel").Message("Hello World from Unity!").ExecuteAsync();

// Publish a Unity object using the GetJsonSafe extension method for handling circular references
await pubnub.Publish().Channel("TestChannel").Message(transform.position.GetJsonSafe()).ExecuteAsync();

// Using a callback instead of async/await
pubnub.Publish()
	.Channel("TestChannel")
	.Message("Hello World from Unity!")
	.Execute((result, status) => {
		if (!status.Error) {
			Debug.Log("Message sent successfully!");
		} else {
			Debug.LogError("Failed to send message: " + status.ErrorData.Information);
		}
	});
```

### Run the app

To test your Unity application:

1. Ensure you have completed all the setup steps.
2. Enter Play mode in Unity Editor.
3. You should see "Connected" in the console log when PubNub connects successfully.
4. When your message is published, you should see it received back in the log.

## Complete example

Here's a complete working example that puts everything together:

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

public class PNManager : PNManagerBehaviour {
	// UserId identifies this client.
	public string userId;

	private async void Awake() {
		if (string.IsNullOrEmpty(userId)) {
			// It is recommended to change the UserId to a meaningful value to be able to identify this client.
			userId = System.Guid.NewGuid().ToString();
		}

		// Listener example.
		listener.onStatus += OnPnStatus;
		listener.onMessage += OnPnMessage;

		// Initialize will create a PubNub instance, pass the configuration object, and prepare the listener.
		Initialize(userId);

		// Modern API example
		Channel channel = pubnub.Channel("TestChannel");
		Subscription subscription = channel.Subscription();
		subscription.Subscribe<object>();

		// Or legacy subscription example
		// pubnub.Subscribe<string>().Channels(new[] { "TestChannel" }).Execute();

		// Publish example
		await pubnub.Publish().Channel("TestChannel").Message("Hello World from Unity!").ExecuteAsync();
	}

	void OnPnStatus(Pubnub pn, PNStatus status) {
		Debug.Log(status.Category == PNStatusCategory.PNConnectedCategory ? "Connected" : "Not connected");
	}

	void OnPnMessage(Pubnub pn, PNMessageResult<object> result) {
		Debug.Log($"Message received: {result.Message}");
	}

	protected override void OnDestroy() {
		// Use OnDestroy to clean up, e.g. unsubscribe from listeners.
		listener.onStatus -= OnPnStatus;
		listener.onMessage -= OnPnMessage;

		base.OnDestroy();
	}
}
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections., Check that SSL is enabled if your network requires it. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered. |
| Script errors | Ensure you've added the PubNub dependency correctly., Make sure all imports are correct., Check that you're using a compatible version of Unity. |
| WebGL build issues | Make sure you've enabled WebGL build mode in the PNConfigAsset., Configure proper WebGL settings following the WebGL configuration guidance. |

## Next steps

Great job! 🎉 You've successfully created your first PubNub application with Unity. Here are some exciting things you can explore next:

### Build a game

* Implement position sync between players using PubNub.
* Create a chat system for your game.
* Develop leaderboards with real-time updates.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/unity/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/unity/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/unity/api-reference/access-manager) to secure your channels.

### Real examples

* Check out the [PubNub Prix demo](https://www.pubnub.com/demos/unity-pubnubprix/) for a full Unity game with leaderboards and chat.
* Explore our [GitHub repository](https://github.com/pubnub/unity/) for more code samples.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **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.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.