You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity+PUN2:如何在RoomInfo中显示自定义房间属性

解决方案

问题核心是Photon不会自动将所有自定义房间属性同步到大厅列表,必须显式指定哪些属性需要在大厅中可见。

1. 修改房间创建代码,标记属性为大厅可见

在设置CustomRoomProperties后,添加代码指定要公开的属性键:

public void startGame()
{
    RoomOptions options = new RoomOptions();
    options.CleanupCacheOnLeave = true;
    options.MaxPlayers = 8; 
    options.IsOpen = true;
    options.IsVisible = true;
    Hashtable RoomCustomProps = new Hashtable();
    RoomCustomProps.Add("availablePods", gameLenghtsIs);
    options.CustomRoomProperties = RoomCustomProps;
    // 新增:标记该属性在大厅可见
    options.CustomRoomPropertiesForLobby = new string[] { "availablePods" };
    PhotonNetwork.JoinOrCreateRoom(createInput.text, options, TypedLobby.Default);
}

2. 安全获取并显示自定义属性

在SetRoomInfo方法中,先判断属性是否存在,再转换为字符串(避免空引用错误):

public void SetRoomInfo(RoomInfo roomInfo)
{
    RoomInfo = roomInfo;
    maxPlayetTxt.text = roomInfo.MaxPlayers + ",";
    nameRoomText.text = roomInfo.Name + ",";
    payerNumberText.text = roomInfo.PlayerCount + "/8";
    
    // 安全获取并显示自定义属性
    if (roomInfo.CustomProperties.TryGetValue("availablePods", out var availablePodsValue))
    {
        podsTxt.text = availablePodsValue.ToString() + ",";
    }
    else
    {
        // 属性不存在时的默认显示
        podsTxt.text = "N/A,";
    }
}

失败原因说明

Photon默认仅同步房间基础信息(名称、玩家数等)到大厅,自定义属性需要通过CustomRoomPropertiesForLobby明确声明后,才会被包含在大厅的RoomInfo对象中。之前的代码未做此配置,所以roomInfo.CustomProperties中不存在availablePods键,自然无法获取到值。

另外注意代码拼写细节:gameLenghtsIs疑似gameLengthIs的笔误,建议检查变量名是否正确。

内容的提问来源于stack exchange,提问作者user3337790

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:15:41