Unity Adăugând chat multiplayer în camerele PUN 2

În acest tutorial, voi arăta cum să adăugați o cameră de chat în PUN 2 folosind RPC-uri (Remote Procedure Calls).

Deci, să începem!

Partea 1: Configurarea PUN 2 și exemplu multiplayer

Avem deja un tutorial despre cum să configurați un exemplu multiplayer cu PUN 2, verificați linkul de mai jos:

Creați un joc multiplayer în Unity 3D folosind PUN 2

Reveniți după ce ați terminat de configurat un proiect multiplayer, astfel încât să putem continua.

Alternativ, puteți descărca direct proiectul sursă.

Partea 2: Adăugarea chatului multiplayer

  • Creați un nou script, numiți-l PUN2_Chat apoi inserați codul de mai jos în interiorul acestuia:

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

Dacă ați urmat tutorialul nostru PUN 2, ați avea acum 2 Scene "GameLobby" și "GameLevel"

  • Deschideți scena "GameLevel" apoi atașați PUN2_Chat la obiectul _RoomController, apoi salvați scena
  • Deschideți scena "GameLobby" apoi creați o cameră nouă, acum ar trebui să puteți conversa prin chat apăsând "T"

Articole sugerate
Faceți un joc multiplayer în Unity folosind PUN 2
Crearea de jocuri multiplayer în rețea în Unity
Creați un joc cu mașini multiplayer cu PUN 2
Photon Network (Clasic) Ghid pentru începători
Comprimarea datelor multiplayer și manipularea biților
Sincronizați corpuri rigide prin rețea folosind PUN 2
PUN 2 Compensare lag