Unity, PUN 2 Odalarına Çok Oyunculu Sohbet Ekliyor

Bu eğitimde, PUN 2'de RPC'leri (Uzaktan Prosedür Çağrıları) kullanarak nasıl oda sohbeti ekleneceğini göstereceğim.

Öyleyse başlayalım!

Bölüm 1: PUN 2'yi ve Çok Oyunculu Örneği Kurma

PUN 2 ile çok oyunculu bir örneğin nasıl kurulacağına dair zaten bir eğitimimiz var, aşağıdaki bağlantıyı kontrol edin:

Unity 3D'te PUN 2'yi kullanarak çok oyunculu bir oyun yapın

Çok oyunculu bir proje oluşturmayı bitirdiğinizde devam edebilmemiz için tekrar gelin.

Alternatif olarak kaynak projesini doğrudan indirebilirsiniz.

Bölüm 2: Çok Oyunculu Sohbet Ekleme

  • yeni bir komut dosyası oluşturun, onu PUN2_Chat olarak adlandırın ve içine aşağıdaki kodu yapıştırın:

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

Eğer PUN 2 eğitimimizi takip ettiyseniz artık 2 Sahneye sahip olacaksınız "GameLobby" ve "GameLevel"

  • "GameLevel" Sahnesini açın, ardından PUN2_Chat'i _RoomController Nesnesine ekleyin ve Sahneyi Kaydedin
  • "GameLobby" Sahnesini açın, ardından yeni bir Oda oluşturun, artık tuşuna basarak sohbet edebilmeniz gerekir. "T"

Önerilen Makaleler
PUN 2'yi kullanarak Unity'de Çok Oyunculu Bir Oyun Yapın
PUN 2 ile Çok Oyunculu Araba Oyunu Yapın
Çok Oyunculu Veri Sıkıştırma ve Bit İşleme
Unity'de Çok Oyunculu Ağ Bağlantılı Oyunlar Oluşturma
PUN 2'yi Kullanarak Sert Cisimleri Ağ Üzerinden Senkronize Etme
Photon Network (Klasik) Başlangıç ​​Kılavuzu
PUN 2 Gecikme Telafisi