In this tutorial, we'll walk through how to build a basic multiplayer lobby chat room with the Unity 3D game engine. This tutorial will work across iOS, Android, Web, and Consoles, so no matter what device you're exporting to, users will be able to chat between devices.
Download the code
Download the full source code from GitHub.
Step 1: Environment Setup
Let's set up the environment first. The first step is to import the PubNub SDK into your Unity project. You can do so by downloading the latest PubNub.unitypackage, then importing that package into Unity by going to Assets -> Import Package -> Custom Package.
Once imported, you may notice you have some errors in your console window. You may need to enable playmode tests for all assemblies.
Step 2: Building the UI
In your application's hierarchy, there are a few essential elements that display chat messages on the screen. The RealtimeChat Scene includes a Main Camera, and a Canvas that renders all of the input fields, buttons, and text objects on the screen. In order for the input fields to be interactive, an EventSystem object is automatically created and displayed in the Hierarchy. Additionally, there are assets such as a simple PNG background, and a Cube to separate the bottom and top sections of the screen.
If you are starting the project from scratch, you will need to create a Main Camera, which should have the SendMessage script attached to it.
Design your user interface however you would like. We placed the loadingCircle on the top right of the screen, and the input fields at the bottom of the screen with the submit button. The chat messages will appear in the middle of the screen and will be removed from the UI once the screen is completely full of messages.
Now that the scene is designed, let's add a script to the Main Camera to develop the chat room interface for the application.
Step 3: Developing the Chatroom Functionality
The first step is to require the PubNub API and other UnityEngine libraries, including
JSONInformation class formats input field data to be published via PubNub.
SendMessage class contains the application’s chatroom logic. We start off by instantiating some public variables and creating a
chatMessageQueue to handle message creation and deletion. Queues are a very powerful data structure in C# that allow objects to be inserted at one end and removed from the other. Queues and stacks are useful when you need temporary storage for information; that is, when you might want to discard an element after retrieving its value.
Now that you have created your public variables, return to your Unity Inspector and drag each element from your Hierarchy into the appropriate fields on your Send Message Script.
Next, let's create the
Start() function. First, login to the PubNub Dashboard to generate your own Publish and Subscribe keys: you will need them in order to get your application to publish and receive messages.
At the top of the
Start() function, we initialize our PubNub instance and create a listener on the button that will run the
TaskOnClick() function when pressed. Next, we fetch the last 13 messages sent on the
chatchannel3 channel (this is simply an example: you can name this channel whatever you wish. If there is an error, print the error in the Unity console; however if there isn't one, we iterate through the last 13 messages and insert them into the
JSONInformation class. Then, run the
CreateChat() function and pass in the chat message to print the data on the screen.
We create a counter for formatting the messages on screen so that messages aren't created past the black line. Next, we subscribe to the
chatchannel3 channel. When an event is published on that channel, it triggers the subscribe callback function. The callback takes the value from the channel event, writes it to the end of the chat history for view, and simultaneously removes the oldest message if there are more than 12 (thus ensuring no more than 13 messages are on screen at the same time).
Next, let's create the
CreateChat() function, which places new text objects onto the screen. The payload information from the PubNub subscribe is passed to the function, and is then assigned to the text object’s Text. Additionally, the function adds the message to the queue and increments the index counter.
SyncChat() function translates all existing messages up on the screen to make room for the new message. Additionally, it deletes the first message on the screen to make room for the new message.
Our last step is to add the functionality that allows a user to send a message. When the user clicks the submit button, they are publishing the message through PubNub, and all subscribed clients with the application open will receive that message in realtime.
That's it! You've just made your first realtime chat application in the Unity 3D game engine.
Add more features
Visit the SDK Reference section to add more features to your app like unread message counts, typing indicators, read receipts, reactions, and more.