</>Demo our Sample Unity Chat App
The example app to the left is a demo of what you’ll be building in this tutorial. . Open up the application in two different browser windows (to represent two unique users), and start sending chat messages between them. You’ll notice messages are sent and received in realtime. PubNub powers this realtime communication between clients and will work on all devices and platforms that Unity exports too.
Unity is a cross-platform game engine open to the developer community, enabling the building and publishing of content created within the game engine. I've been developing with Unity for a number of years; however creating multiplayer games and experiences has always been one of the most challenging hurdles on the platform. Using PubNub with Unity, though, makes creating realtime games significantly easier.
PubNub allows developers to build low-latency, realtime applications that perform reliably and securely, at global scale. All you have to do is write the front-end code with PubNub's easy-to-use API's, and PubNub handles all the infrastructure for you. This is especially important in the game development industry, as it mitigates the risk of multiplayer server downtime in the event that your game grows faster than expected.
In this tutorial, we'll walk through how to build a basic multiplayer game lobby chat room using the Unity 3D game engine. This tutorial will work across iOS, Android, Web and Video Game Consoles, so no matter what device you are exporting to, users will be able to chat between devices. PubNub can also power the realtime interactions between players in your game, not just chat. This makes the possibilities endless with the PubNub API.
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. If you are seeing Error CS0234: The type or namespace name 'TestTools' does not exist. Fix this problem by going to: Window -> General -> Test Runner; then click on the drop-down menu in the top right corner and enable playmode tests for all assemblies.
Note: If you download the GitHub repo, you won't have to re-import the PubNub package. You will only have to enable the Test Runner. Download that the repo here.
The GitHub repo should include four folders. Assets, PubNub, Scenes and Scripts. In the Assets folder, there is a background image, submit button, font files and a loading circle. In the Scripts folder, there are the two scripts: SendMessage and LoadingCircle. The SendMessage script is where we will be writing the code to send and receive messages from clients in realtime.
In your applications 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 background, which is a simple PNG; 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 has been designed, let's add a script to the Main Camera to develop the chat room interface for the application.
TThe first step is to require the PubNub API and other UnityEngine libraries, including UnityEngine.ui. The class JSONInformation is where input field data will be formatted to be published via PubNub.
The class SendMessage is where all of the application’s chatroom logic will be written. 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. Learn more about queues on the Microsoft .Net documentation page.
Now that you have created your public variables, make sure to 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 fill out and submit the form below to generate your own PubNub Publish and Subscribe keys: you will need them in order to get your application to publish and receive messages.
In the beginning of the Start() function, we initialize PubNub and create a listener on the button that will run the TaskOnClick() function when pressed. Next, we fetch the last 13 messages that were sent on the PubNub Channel chatchannel3 (you can name this channel whatever you wish, this just what I chose to name it in my project). If there is an error, print the error in the Unity console, however if there isn't one, iterate through the last 13 messages and insert them into the class JSONInformation. Then run the function CreateChat() and pass the chat message to that function to print the data on the screen.
We create a counter for formating the messages on screen so that messages aren't created past the black line. Next, we subscribe to the PubNub channel "chatchannel3": now 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 will be responsible for placing new text objects onto the screen whenever the function is called. The payload information from the PubNub subscribe is passed through the function, and then is assigned to the text object’s Text. Additionally, the message is added to the queue and the index counter is iterated.
Now that the CreateChat() function has been created, we’ll add functionality that translates all existing messages up on the screen to make room for the new message. Additionally, let's delete 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. In clicking the submit button, the user is publishing the message through PubNub. When a message is published, all subscribed clients with the application open will receive that message in realtime.
Note, we also need to reset the text field to be blank once the message has been submitted.
That's it folks! Yes, it's really that easy to make your first realtime chat application in the Unity 3D game engine. If you ran into any roadblocks with the tutorial, feel free to reach out to me at firstname.lastname@example.org. You can download the source code here!