Unity API & SDK Docs v8.2.0
In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNubPubNub
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
- 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.
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.
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 or create an account on the PubNub Admin Portal.
- Create a new app (or use an existing one).
- Find your publishand subscribe
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.keys in the app's dashboard.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.
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
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)
-
Open Unity Editor and navigate to Window -> Package Manager.
-
In the Package Manager window, click + and select Add package from git URL.
-
Paste the PubNub Unity package link and click Add.
https://github.com/pubnub/unity.git?path=/PubNubUnity/Assets/PubNub
-
Navigate to PubNub in the editor menu bar and click Set up templates.
-
Restart Unity Editor.
Get the source code
If you prefer to get the source code directly:
https://github.com/pubnub/unity.git?path=/PubNubUnity/Assets/PubNub
Steps
Configure PubNub
Unity provides a unique way to configure PubNub through the editor interface without writing code:
-
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.
-
Open the newly created
PNConfigAsset
scriptable object and provide your publish and subscribe keys. Other configuration items are optional.UserId requirement
Every 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.
-
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.
-
Drag the
PnManager
script onto any game object in your scene. This addsPnManager
as a component. -
Drag the
PNConfigAsset
onto the PubNub Configuration field inside PnManager (Script).
Alternatively, you can configure PubNub programmatically:
// Create a configuration object
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "demo"; // Replace with your publish key
pnConfiguration.SubscribeKey = "demo"; // Replace with your subscribe key
pnConfiguration.Secure = true; // Enable SSL
// Initialize PubNub with this configuration
Pubnub pubnub = new Pubnub(pnConfiguration);
For more information, refer to the 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
// Add listeners to handle incoming events
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 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:
- Define a channel to subscribe to.
- Call
Subscribe()
with the channel name. - Set up event listeners to handle incoming messages.
// 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();
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 JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.
// 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);
show all 17 linesRun the app
To test your Unity application:
- Ensure you have completed all the setup steps.
- Enter Play mode in Unity Editor.
- You should see "Connected" in the console log when PubNub connects successfully.
- 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:
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
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();
}
show all 51 linesTroubleshooting
If you don't see the expected output, here are some common issues and how to fix them:
Issue | Possible Solutions |
---|---|
No connection message |
|
Message not received |
|
Script errors |
|
WebGL build issues |
|
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
- Advanced features
- Real examples
- More help
- Implement position sync between players using PubNub.
- Create a chat system for your game.
- Develop leaderboards with real-time updates.
- Try out Presence to track online/offline status.
- Implement Message Persistence to store and retrieve messages.
- Use Access Manager to secure your channels.
- Check out the PubNub Prix demo for a full Unity game with leaderboards and chat.
- Explore our GitHub repository for more code samples.
- Check out our SDK reference documentation for detailed API information.
- Visit our support portal for additional resources.
- Ask our AI assistant (the looking glass icon at the top of the page) for help.