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 个场景 "GameLobby" 和 "GameLevel"

  • 打开 "GameLevel" 场景,然后将 PUN2_Chat 附加到 _RoomController 对象,然后保存场景
  • 打开 "GameLobby" 场景,然后创建一个新房间,您现在应该可以通过按 "T"

推荐文章
使用 PUN 2 在 Unity 中制作多人游戏
使用 PUN 2 制作多人汽车游戏
使用 PUN 2 通过网络同步刚体
PUN 2 滞后补偿
光子网络(经典)初学者指南
在 Unity 中构建多人网络游戏
多人数据压缩和位操作