Unity Aggiunta della chat multigiocatore alle stanze di PUN 2

In questo tutorial, mostrerò come aggiungere una chat room in PUN 2 utilizzando le RPC (Remote Procedure Calls).

Allora cominciamo!

Parte 1: Impostazione del PUN 2 ed esempio multigiocatore

Abbiamo già un tutorial su come impostare un esempio multiplayer con PUN 2, controlla il link qui sotto:

Crea una partita multiplayer in Unity 3D usando PUN 2

Torna una volta che hai finito di impostare un progetto multiplayer così possiamo continuare.

In alternativa, puoi scaricare direttamente il progetto sorgente.

Parte 2: aggiunta della chat multigiocatore

  • Crea un nuovo script, chiamalo PUN2_Chat quindi incolla al suo interno il codice seguente:

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);
        }
    }
}

Se seguissi il nostro tutorial PUN 2 ora avresti 2 scene "GameLobby" e "GameLevel"

  • Apri la scena "GameLevel", quindi collega PUN2_Chat all'oggetto _RoomController, quindi salva la scena
  • Apri la scena "GameLobby" quindi crea una nuova stanza, ora dovresti essere in grado di chattare premendo "T"

Articoli suggeriti
Crea un gioco multiplayer in Unity usando PUN 2
Realizza un gioco di auto multiplayer con PUN 2
Photon Network (Classic) Guida per principianti
Compressione dei dati multigiocatore e manipolazione dei bit
Sincronizza i corpi rigidi sulla rete usando PUN 2
PUN 2 Compensazione ritardo
Creazione di giochi in rete multiplayer in Unity