Unity3D学习——使用PUN写一个聊天功能
生活随笔
收集整理的這篇文章主要介紹了
Unity3D学习——使用PUN写一个聊天功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PUN,即Photon Unity Networking,它是一個Unity多人游戲插件包。它提供了身份驗證選項、匹配,以及快速、可靠的通過我們的Photon后端實現的游戲內通信。
在實現聊天功能之前,你需要把PUN導入到你的項目中來,并完成玩家加入房間等功能。
?
現在,我已經寫好了一個房間,并讓兩個玩家加入了房間內
?
并且寫好了聊天框,聊天框要掛載photonview組件
?
下面是關鍵代碼
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Collections;[RequireComponent(typeof(PhotonView))] public class InRoomChat : Photon.MonoBehaviour {//聲明變量public Rect GuiRect;public bool IsVisible = true;public bool AlignBottom = false;public List<string> messages = new List<string>();private string inputLine = "";public Vector2 scrollPos;public InputField inputMessage;public GameObject btnSend;public GameObject lblRoomMessage;public static readonly string ChatRPC = "Chat";public void Start(){FindObject();}//加載需要的對象public void FindObject(){inputMessage = GameObject.Find("inputRoomMessage").GetComponent<InputField>();btnSend = GameObject.Find("btnRoomMessage");lblRoomMessage = GameObject.Find("lblRoomMessage");if (btnSend != null){btnSend.GetComponent<Button>().onClick.AddListener(delegate { SendContent(); });}}//發送聊天內容public void SendContent(){if (!this.IsVisible || !PhotonNetwork.inRoom){return;}//獲取聊天框內容inputLine = inputMessage.text;if (!string.IsNullOrEmpty(this.inputLine)){lblRoomMessage.GetComponent<Text>().text = "";//關鍵代碼 使用photonView.RPC發送消息this.photonView.RPC("Chat", PhotonTargets.All, this.inputLine);this.inputLine = "";inputMessage.text = "";inputMessage.ActivateInputField();}else{return;}}//接收方收取消息[PunRPC]public void Chat(string newLine, PhotonMessageInfo mi){string senderName = "anonymous";lblRoomMessage.GetComponent<Text>().text = "";if (mi.sender != null){if (!string.IsNullOrEmpty(mi.sender.NickName)){senderName = mi.sender.NickName;}else{senderName = "player " + mi.sender.ID;}}this.messages.Add("<color=#EEAD0E>" + senderName +":</color> " + newLine);//只顯示最新的24條消息List<string> newmessages = new List<string>();if (messages.Count > 24){for (int i = (messages.Count - 24); i < messages.Count; i++){newmessages.Add(messages[i]);}for (int i = 0; i < newmessages.Count; i++){lblRoomMessage.GetComponent<Text>().text += newmessages[i] + "\n";}}else{for (int i = 0; i < messages.Count; i++){lblRoomMessage.GetComponent<Text>().text += messages[i] + "\n";}}}public void AddLine(string newLine){this.messages.Add(newLine);} }關鍵的代碼就是這一句,?photonView組件自帶的功能,第一個參數是接收方法,第三個參數是聊天內容
this.photonView.RPC("Chat", PhotonTargets.All, this.inputLine);
?接收方的方法,前面要帶上[PunRPC]
? ? [PunRPC]
? ? public void Chat(string newLine, PhotonMessageInfo mi)
{
//接收后的處理
}
?
就是這些了,省略了一些其他部分的內容。希望這篇文檔能有幫助。
總結
以上是生活随笔為你收集整理的Unity3D学习——使用PUN写一个聊天功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PUN介绍(干货)
- 下一篇: 工业产品常用的长度单位有哪些?