Unity, PUN 2 룸에 멀티플레이어 채팅 추가

이 튜토리얼에서는 RPC(원격 프로시저 호출)를 사용하여 PUN 2에 룸 채팅을 추가하는 방법을 보여 드리겠습니다.

그럼 시작해보자!

1부: PUN 2 및 멀티플레이어 예제 설정

PUN 2를 사용하여 멀티플레이어 예제를 설정하는 방법에 대한 튜토리얼이 이미 있습니다. 아래 링크를 확인하세요.

PUN 2를 사용하여 Unity 3D에서 멀티플레이어 게임 만들기

계속할 수 있도록 멀티플레이어 프로젝트 설정을 마친 후 다시 돌아오세요.

또는 소스 프로젝트을 직접 다운로드할 수도 있습니다.

2부: 멀티플레이어 채팅 추가

  • 새 스크립트를 생성하고 PUN2_Chat이라고 명명한 다음 그 안에 아래 코드를 붙여넣습니다.

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

PUN 2 튜토리얼을 따랐다면 이제 2개의 Scene "GameLobby"과 "GameLevel"

  • "GameLevel" 장면을 열고 PUN2_Chat을 _RoomController 개체에 연결한 다음 장면을 저장합니다.
  • "GameLobby" 장면을 연 다음 새 방을 만듭니다. 이제 다음을 눌러 채팅할 수 있습니다. "T"

추천 기사
PUN 2를 사용하여 Unity에서 멀티플레이어 게임 만들기
PUN 2를 사용하여 네트워크를 통해 강체 동기화
Photon 네트워크(클래식) 초보자 가이드
PUN 2로 멀티플레이어 자동차 게임 만들기
멀티플레이어 데이터 압축 및 비트 조작
Unity에서 멀티플레이어 네트워크 게임 구축
PUN 2 지연 보상