How to Build Realtime Chat with Unity


Scroll down to start the step by step tutorial

</> 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.

void TaskOnClick()
    {
        // When the user clicks the Submit button,
        // create a JSON object from input field input
        JSONInformation publishMessage = new JSONInformation();
        publishMessage.username = string.Concat(UsernameInput.text, ": ");
        publishMessage.text = TextInput.text;
        string publishMessageToJSON = JsonUtility.ToJson(publishMessage);

        // Publish the JSON object to the assigned PubNub Channel
        pubnub.Publish()
            .Channel("chatchannel3")
            .Message(publishMessageToJSON)
            .Async((result, status) =>
            {
                if (status.Error)
                {
                    Debug.Log(status.Error);
                    Debug.Log(status.ErrorData.Info);
                }
                else
                {
                    Debug.Log(string.Format(result.Timetoken));
                }
            });

        // Reset the text field to be blank
        TextInput.text = "";
    }

GitHub Install

git clone https://github.com/JordanSchuetz/Unity-Realtime-Chat-Room-Tutorial.git

Unity Realtime Chat Tutorial

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.

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. 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.

Step 2: Building the UI

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.

Step 3: Developing the Realtime Chatroom Functionality

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.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PubNubAPI;
using UnityEngine.UI;

public class JSONInformation
{
    public string username;
    public string text;
}

public class SendMessage : MonoBehaviour {
    public static PubNub pubnub;
    public Font customFont;
    public Button SubmitButton;
    public Canvas canvasObject;
    public InputField UsernameInput;
    public InputField TextInput;
    public int counter = 0;
    public int indexcounter = 0;
    public Text deleteText;
    public Text moveTextUpwards;
    private Text text;

    Queue<GameObject> chatMessageQueue = new Queue<GameObject>();
   
    void Start(){

    }

    void CreateChat(JSONInformation payLoad){

    }

    void SyncChat() {
       
    }

    void Update () {

    }
    void TaskOnClick(){

    }
}

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)

void Start()
    {
        // Use this for initialization
        PNConfiguration pnConfiguration = new PNConfiguration();
        pnConfiguration.PublishKey = "YOUR-KEYS-HERE";
        pnConfiguration.SubscribeKey = "YOUR-KEYS-HERE";
        pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
        pnConfiguration.UUID = System.Guid.NewGuid().ToString();
        pubnub = new PubNub(pnConfiguration);

        // Add Listener to Submit button to send messages
        Button btn = SubmitButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);

        // Fetch the last 13 messages sent on the given PubNub channel
        pubnub.FetchMessages()
            .Channels(new List<string> { "chatchannel3" })
            .Count(13)
            .Async((result, status) =>
            {
            if (status.Error)
            {
                Debug.Log(string.Format(
                    " FetchMessages Error: {0} {1} {2}", 
                    status.StatusCode, status.ErrorData, status.Category
                ));
            }
            else
            {
                foreach (KeyValuePair<string, List<PNMessageResult>> kvp in result.Channels)
                {
                    foreach (PNMessageResult pnMessageResult in kvp.Value)
                    {
                        // Format data into readable format
                        JSONInformation chatmessage = JsonUtility.FromJson<JSONInformation>(pnMessageResult.Payload.ToString());

                        // Call the function to display the message in plain text
                        CreateChat(chatmessage);

                        // Counter used for positioning the text UI 
                        if (counter != 650)
                        {
                            counter += 50;
                        }
                    }
                 }
             }
             });

        // Subscribe to a PubNub channel to receive messages when they are sent on that channel
        pubnub.Subscribe()
            .Channels(new List<string>() {
                "chatchannel3"
            })
            .WithPresence()
            .Execute();

        // This is the subscribe callback function where data is recieved that is sent on the channel
        pubnub.SusbcribeCallback += (sender, e) =>
        {
            SusbcribeEventEventArgs message = e as SusbcribeEventEventArgs;
            if (message.MessageResult != null)
            {
                // Format data into a readable format
                JSONInformation chatmessage = JsonUtility.FromJson<JSONInformation>(message.MessageResult.Payload.ToString());

                // Call the function to display the message in plain text
                CreateChat(chatmessage);

                // When a new chat is created, remove the first chat and transform all the messages on the page up
                SyncChat();

                // Counter used for position the text UI
                if (counter != 650)
                {
                    counter += 50;
                }
            }
        };
    }

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.

// Function used to create new chat objects based of the data received from PubNub
void CreateChat(JSONInformation payLoad){
  // Create a string with the username and text
  string currentObject = string.Concat(payLoad.username, payLoad.text);

  // Create a new gameobject that will display text of the data sent via PubNub
  GameObject chatMessage = new GameObject(currentObject);
  chatMessage.transform.SetParent(canvasObject.GetComponent<Canvas>().transform);
  chatMessage.AddComponent<Text>().text = currentObject;

  // Assign text to the gameobject. Add visual properties to text
  var chatText = chatMessage.GetComponent<Text>();
  chatText.font = customFont;
  chatText.color = UnityEngine.Color.black;
  chatText.fontSize = 35;

  // Assign a RectTransform to gameobject to maniuplate positioning of chat.
  RectTransform rectTransform;
  rectTransform = chatText.GetComponent<RectTransform>();
  rectTransform.localPosition = new Vector2(-10, 430 - counter);
  rectTransform.sizeDelta = new Vector2(650, 50);
  rectTransform.localScale = new Vector3(1F, 1F, 1F);

  // Assign the gameobject to the queue of chatmessages
  chatMessageQueue.Enqueue(chatMessage);

  // Keep track of how many objects we have displayed on the screen
  indexcounter++;
}

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.

void SyncChat() {
  // If more 13 objects are on the screen, we need to start removing them
  if (indexcounter >= 14)
  {
      // Delete the first gameobject in the queue
      GameObject deleteChat = chatMessageQueue.Dequeue();
      Destroy(deleteChat);

      // Move all existing text gameobjects up the Y axis 50 pixels
      foreach (GameObject moveChat in chatMessageQueue)
      {
          RectTransform moveText = moveChat.GetComponent<RectTransform>();
          moveText.offsetMax = new Vector2(moveText.offsetMax.x, moveText.offsetMax.y + 50);
      }
  }
}

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.

void TaskOnClick()
{
  // When the user clicks the Submit button,
  // create a JSON object from input field input
  JSONInformation publishMessage = new JSONInformation();
  publishMessage.username = string.Concat(UsernameInput.text, ": ");
  publishMessage.text = TextInput.text;
  string publishMessageToJSON = JsonUtility.ToJson(publishMessage);

  // Publish the JSON object to the assigned PubNub Channel
  pubnub.Publish()
      .Channel("chatchannel3")
      .Message(publishMessageToJSON)
      .Async((result, status) =>
      {
          if (status.Error)
          {
              Debug.Log(status.Error);
              Debug.Log(status.ErrorData.Info);
          }
          else
          {
            Debug.Log(string.Format("Publish Timetoken: {0}", result.Timetoken));
          }
      });

  TextInput.text = "";
}

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 schuetz@pubnub.com. You can download the source code here!

Share