c# - 不在大厅时使用 LoadBalancingClient 轮询可用的 Unity Photon 房间?

标签 c# unity3d photon

使用 Unity、C# 和 Photon (PUN2),我已经让用户连接到一个房间,但现在想(在该用户不离开房间的情况下)检索当前可用的其他 Photon 房间的列表,包括他们当前的在线用户计数(通常只能在大厅中加入房间之前或之后完成)。 Photon 支持告诉我,我需要为此使用 LoadBalancingClient 创建第二个客户端,但我不知 Prop 体怎么做。基本 Connect - PollAvailableRoomsAndOnlineCounts - Disconnect 类和过程的代码框架是什么?谢谢!

最佳答案

同时找到了答案。这是我的助手类 PhotonRoomPoller.cs 的框架代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using ExitGames.Client.Photon;

public class PhotonRoomPoller : MonoBehaviourPunCallbacks
{
    // Creates a second Photon peer to poll online room counts info.
    // A second peer is necessary as one otherwise while in a Room can't join
    // the Lobby, needed to get the room list. API at
    // doc-api.photonengine.com/en/pun/v2/class_photon_1_1_realtime_1_1_load_balancing_client.html

    Action<List<RoomInfo>> callback = null;
    LoadBalancingClient client = null;

    public void GetRoomsInfo(Action<List<RoomInfo>> callback)
    {
        this.callback = callback;

        client = new LoadBalancingClient();
        client.AddCallbackTarget(this);
        client.StateChanged += OnStateChanged;
        client.AppId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime;
        client.AppVersion = PhotonNetwork.NetworkingClient.AppVersion;
        client.ConnectToRegionMaster("us");
    }

    void Update()
    {
        if (client != null)
        {
            client.Service();
        }
    }

    void OnStateChanged(ClientState previousState, ClientState state)
    {
        // Debug.Log(state);
        if (state == ClientState.ConnectedToMaster)
        {
            client.OpJoinLobby(null);
        }
    }

    public override void OnRoomListUpdate(List<RoomInfo> infos)
    {
        if (callback != null)
        {
            callback(infos);
        }
        client.Disconnect();
    }

}

用法,例如:

PhotonRoomPoller roomPoller = gameObject.AddComponent<PhotonRoomPoller>();
roomPoller.GetRoomsInfo
(
    (roomInfos) =>
    {
        AddContent(roomInfos);
        Destroy(roomPoller);
    }
);

需要特别注意match all needed settings (尽管很多也可以保持为 null 或未定义,例如 gameVersion)。

关于c# - 不在大厅时使用 LoadBalancingClient 轮询可用的 Unity Photon 房间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57366704/

相关文章:

c# - 在 gridview 文本框中自动完成

c# - 如何将一个 mvc3 c# 项目添加到其他可执行项目中?

c# - 将 Azure 网站连接到 Xero 合作伙伴应用程序

c# - 实例化的预制比例在客户端上显示不正确

c# - 对多个 WPF 控件应用类似的绑定(bind)

c# - 在 Android 上的 Unity 中从 C++ DLL 访问 StreamingAssets 资源

c# - 如何在 Unity3D 中将特定音频源静音?

android - 在Android上从Particle Photon触发音频

c# - Photon Networking Unity AllProperties 未设置

c# - 如何使用光子统一在固定位置生成多人游戏用户?