Unity3D学习——使用PUN写一个聊天功能

PUN,即Photon Unity Networking,它是一个Unity多人游戏插件包。它提供了身份验证选项、匹配,以及快速、可靠的通过我们的Photon后端实现的游戏内通信。

在实现聊天功能之前,你需要把PUN导入到你的项目中来,并完成玩家加入房间等功能。

 

现在,我已经写好了一个房间,并让两个玩家加入了房间内

Unity3D学习——使用PUN写一个聊天功能_第1张图片

 

并且写好了聊天框,聊天框要挂载photonview组件

Unity3D学习——使用PUN写一个聊天功能_第2张图片

Unity3D学习——使用PUN写一个聊天功能_第3张图片

 

下面是关键代码

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 messages = new List();
    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();
        btnSend = GameObject.Find("btnRoomMessage");
        lblRoomMessage = GameObject.Find("lblRoomMessage");
        if (btnSend != null)
        {
            btnSend.GetComponent

关键的代码就是这一句, photonView组件自带的功能,第一个参数是接收方法,第三个参数是聊天内容

this.photonView.RPC("Chat", PhotonTargets.All, this.inputLine);

 接收方的方法,前面要带上[PunRPC]

    [PunRPC]
    public void Chat(string newLine, PhotonMessageInfo mi)

{

//接收后的处理

}

 

就是这些了,省略了一些其他部分的内容。希望这篇文档能有帮助。

你可能感兴趣的:(游戏开发)