Photon PUN刷新大厅房间列表

本文档介绍了如何修复 PhotonPUN 在创建和管理房间时出现的更新问题,以及如何主动获取和刷新房间列表。通过设置自定义房间属性和使用TypedLobby,实现了更精确的房间筛选。此外,还讨论了根据房间状态动态切换按钮的行为,利用哈希值传递游戏状态信息。文章提供了一种方法来确保玩家能及时获取房间状态更新,并提供了源码供交流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言

在早些时候,我写过一篇《使用Photon PUN创建简单对战游戏》的联机教程,这篇教程只是很简单的实现了更新房间、创建房间、加入房间的功能,其中还有很多的BUG,需要进行修复。最近因为要用到Photon PUN这个插件,所以又进行了一些探索,今天主要是针对更新房间这个操作进行进一步实现,如果想看原生的官方教程,可以查看Photon官网

初始准备

前期的准备可以参考我之前的那篇文章,今天主要是针对房间更新这个BUG进行修复。为了有更好的联机服务,我也向Photon的中国光子云申请了中国区APPid,申请官网
完成申请之后要更改一些东西,首先回到unity中,找到LoadBalancingClient.cs这个脚本,修改这一行的内容为
在这里插入图片描述
再更改固定地区为cn
在这里插入图片描述

在开始实现之前,我们先思考一下,大厅的房间列表更新一般会有哪几种情况,我这里罗列了三种:
1.房主建好房间,但未开始游戏,此时别的玩家进入大厅需要更新房间列表,玩家可以进行准备
2.房主建好房间,已开始游戏,此时别的玩家进入大厅需要更新房间列表,玩家可以直接进入游戏
3.房主和玩家都退出房间,此时需要更新大厅房间列表

这三种并不代表所有情况,但是都需要一个功能,那就是随时随地更新房间列表,而不是当房间信息更新时进行更新,所以我们需要主动去触发房间更新,然后获取到列表里面,这里就引入了Photon PUN里面的一些新功能。在大厅界面,我们新建一个按钮用来主动更新房间列表,然后为其绑定事件函数。
在这里插入图片描述
我们回到之前写的加入或创建房间的回调事件中,进行一些修改,加入的时候设置了大厅类型

    /// <summary>
    /// 当成功连接该服务器
    /// </summary>
    public override void OnConnectedToMaster()
    {
        NamePanel.SetActive(true);//显示名字面板
        StartInitPanel.SetActive(false);//隐藏开始初始化面板
        TypedLobby typedLobby = new TypedLobby("customSqlLobby", LobbyType.SqlLobby);//设置当前大厅类型为sqllobby
        PhotonNetwork.JoinLobby(typedLobby);//加入大厅
        Debug.Log("加入大厅成功");
    }

在创建房间的按钮事件里,进行修改,添加两个筛选的条件,可以理解为这个房间的自定义的参数,主要为了,Photon官方的解释就是类似数据库的筛选条件,可以更加精确地区分你的房间。这里我们随便设置了两个参数,参数的类型和命名由你自己定,注意命名不能以下面的方式进行。

    public const string ELO_PROP_KEY = "C0";
    public const string MAP_PROP_KEY = "C1";
    /// <summary>
    /// 创建或加入房间按钮
    /// </summary>
    public void joinOrCreateRoomBtn()
    {
        if (RoomnameInputField.text.Length <= 2)
        {
            return;
        }
        LobbyPanel.SetActive(false);
        RoomOptions roomOptions = new RoomOptions { MaxPlayers = 4,IsOpen=true};//房间最大人数4人
        roomOptions.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable { { ELO_PROP_KEY, 100 }, { MAP_PROP_KEY, "Map1" } };
        roomOptions.CustomRoomPropertiesForLobby = new string[] { ELO_PROP_KEY,MAP_PROP_KEY};
        PhotonNetwork.JoinOrCreateRoom(RoomnameInputField.text, roomOptions, default);
        RoomPanel.SetActive(true);

    }

不能使用的命名参数:
ALTER
CREATE
DELETE
DROP
EXEC
EXECUTE
INSERT
INSERT INTO
MERGE
SELECT
UPDATE
UNION
UNION ALL

接下来我们写一个获取房间列表的函数和按钮事件

/// <summary>
    /// 获取到房间列表的函数,传入sql大厅筛选参数
    /// </summary>
    /// <param name="sqlLobbyFilter"></param>
    private void GetCustomRoomList(string sqlLobbyFilter)
    {
        //新建一个大厅类型,
        TypedLobby typedLobby = new TypedLobby("customSqlLobby", LobbyType.SqlLobby);
        bool isgetsuce=PhotonNetwork.GetCustomRoomList(typedLobby, sqlLobbyFilter);
      
        if (isgetsuce)
        {
            Debug.Log("获取房间列表成功");
        }
        else
        {
            Debug.Log("获取失败");
        }
    }
    public void UpdateRoomInfoBtn()
    {
        GetCustomRoomList("C1='Map1'");
    }

如此,就可以进行主动刷新了。
但是,刚才讲到房主未开始游戏时,玩家进去之后会有一个准备按钮,但是如果房主已经开始游戏,此时就要切换成进入游戏按钮,所以这里需要进行一些修改,会用到一个非常实用的功能,就是photon里面的哈希值设置,具体用法如下:

   //设置参数  我这里设置的是游戏是否已经开始的一个参数
   ExitGames.Client.Photon.Hashtable MGameState = new ExitGames.Client.Photon.Hashtable();
   MGameState["gamestate"] = 1;//1代表游戏进行中    0代表游戏未开始
   PhotonNetwork.CurrentRoom.SetCustomProperties(MGameState);
//获取参数  
            if (PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("gamestate"))
            {
                if ((int)(PhotonNetwork.CurrentRoom.CustomProperties["gamestate"]) == 1)
                {
                    readyBtn.SetActive(false);
                    startBtn.SetActive(false);
                    enterGameBtn.SetActive(true);
                }
                else
                {
                    readyBtn.SetActive(true);
                    startBtn.SetActive(false);
                    enterGameBtn.SetActive(false);
                }
                print(PhotonNetwork.CurrentRoom.CustomProperties["gamestate"]); 
            
            }

其实只要可以同时设置这个,就可以分发到其他玩家那里,对应的步骤也就简单了,不过我这里建议满四个人或者固定人数开始游戏比较好,如果没有达到相应的人数,就不能开始游戏。当然也可以尝试一下不满人就加入,这里我技术水平有限,还遇到一些问题,需要后面再解决,有想法的大佬可以交流一下啊。需要项目源码可以私聊我,我们一起交流一下。
在这里插入图片描述

### Photon PunRPC Usage and Documentation for Networked Game Development In the context of developing networked games using Photon, `PunRPC` (Photon Unreliable Remote Procedure Call) serves a critical role in facilitating communication between clients within a multiplayer environment. This mechanism allows developers to invoke methods on all connected players or specific ones from one client. #### Defining and Using PunRPC Methods To utilize `PunRPC`, developers must define methods that can be called remotely across different instances of the game running on various devices. These methods are marked with `[PunRPC]` attribute which signifies them as callable via RPC mechanisms provided by Photon[^1]. ```csharp using Photon.Pun; using UnityEngine; public class ExamplePlayer : MonoBehaviourPunCallbacks { void Start() { photonView.RPC("ExampleMethod", RpcTarget.All); } [PunRPC] void ExampleMethod() { Debug.Log("This method was invoked through PunRPC."); } } ``` The above code snippet demonstrates how to declare an RPC method (`ExampleMethod`) and call it so that every player receives this invocation. The parameter `RpcTarget.All` specifies that the message should reach all participants including the sender itself; other options like `RpcTarget.Others`, `RpcTarget.MasterClient`, etc., allow more targeted broadcasting based on requirements. #### Reliability Considerations It is important to note that while named "Unreliable," many operations performed over `PunRPC` do indeed offer reliable delivery guarantees depending upon configuration settings chosen during setup phases. Developers have control over whether messages sent via these calls need acknowledgment receipts ensuring they arrive at destinations without loss even under less-ideal networking conditions. #### Security Implications When implementing remote procedure calls within applications, especially those exposed online where external parties might attempt unauthorized access attempts, proper validation checks become paramount. Ensuring only legitimate actions trigger such events helps mitigate potential vulnerabilities associated with exposing internal logic externally[^2]. --related questions-- 1. How does Photon handle synchronization issues when multiple users interact simultaneously? 2. What alternatives exist besides PunRPC for inter-client communications in Unity-based multiplayer games? 3. Can you provide examples demonstrating secure implementation practices around PunRPC functions? 4. In what scenarios would someone prefer using reliable versus unreliable modes offered by PunRPC?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ToDoNothing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值