Unity Adding Multiplayer Chat to the PUN 2 Rooms

In this tutorial, I will be showing how to add a room chat in PUN 2 using RPCs (Remote Procedure Calls).

So let's begin!

Part 1: Setting Up PUN 2 and Multiplayer Example

We already have a tutorial on how to set up a multiplayer example with PUN 2, check the link below:

Make a multiplayer game in Unity 3D using PUN 2

Come back once you are done setting up a multiplayer project so we can continue.

Alternatively, you can download the source project directly.

Part 2: Adding Multiplayer Chat

  • Create a new script, call it PUN2_Chat then paste the code below inside it:

PUN2_Chat.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class PUN2_Chat : MonoBehaviourPun
{
    bool isChatting = false;
    string chatInput = "";

    [System.Serializable]
    public class ChatMessage
    {
        public string sender = "";
        public string message = "";
        public float timer = 0;
    }

    List<ChatMessage> chatMessages = new List<ChatMessage>();

    // Start is called before the first frame update
    void Start()
    {
        //Initialize Photon View
        if(gameObject.GetComponent<PhotonView>() == null)
        {
            PhotonView photonView = gameObject.AddComponent<PhotonView>();
            photonView.ViewID = 1;
        }
        else
        {
            photonView.ViewID = 1;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.T) && !isChatting)
        {
            isChatting = true;
            chatInput = "";
        }

        //Hide messages after timer is expired
        for (int i = 0; i < chatMessages.Count; i++)
        {
            if (chatMessages[i].timer > 0)
            {
                chatMessages[i].timer -= Time.deltaTime;
            }
        }
    }

    void OnGUI()
    {
        if (!isChatting)
        {
            GUI.Label(new Rect(5, Screen.height - 25, 200, 25), "Press 'T' to chat");
        }
        else
        {
            if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
            {
                isChatting = false;
                if(chatInput.Replace(" ", "") != "")
                {
                    //Send message
                    photonView.RPC("SendChat", RpcTarget.All, PhotonNetwork.LocalPlayer, chatInput);
                }
                chatInput = "";
            }

            GUI.SetNextControlName("ChatField");
            GUI.Label(new Rect(5, Screen.height - 25, 200, 25), "Say:");
            GUIStyle inputStyle = GUI.skin.GetStyle("box");
            inputStyle.alignment = TextAnchor.MiddleLeft;
            chatInput = GUI.TextField(new Rect(10 + 25, Screen.height - 27, 400, 22), chatInput, 60, inputStyle);

            GUI.FocusControl("ChatField");
        }
        
        //Show messages
        for(int i = 0; i < chatMessages.Count; i++)
        {
            if(chatMessages[i].timer > 0 || isChatting)
            {
                GUI.Label(new Rect(5, Screen.height - 50 - 25 * i, 500, 25), chatMessages[i].sender + ": " + chatMessages[i].message);
            }
        } 
    }

    [PunRPC]
    void SendChat(Player sender, string message)
    {
        ChatMessage m = new ChatMessage();
        m.sender = sender.NickName;
        m.message = message;
        m.timer = 15.0f;

        chatMessages.Insert(0, m);
        if(chatMessages.Count > 8)
        {
            chatMessages.RemoveAt(chatMessages.Count - 1);
        }
    }
}

If you followed our PUN 2 tutorial you would now have 2 Scenes "GameLobby" and "GameLevel"

  • Open the "GameLevel" Scene then attach PUN2_Chat to _RoomController Object then Save the Scene
  • Open the "GameLobby" Scene then create a new Room, you should now be able to chat by pressing "T"

Suggested Articles
Make a Multiplayer Game in Unity using PUN 2
Make a Multiplayer Car Game with PUN 2
Photon Network (Classic) Beginner's Guide
Multiplayer Data Compression and Bit Manipulation
Sync Rigidbodies Over Network Using PUN 2
Building Multiplayer Networked Games in Unity
Unity Online Leaderboard Tutorial