光子网络 Player.SetCustomProperties 不工作

Photon Network Player.SetCustomProperties not working

我目前正在使用 Unity 使用 Photon Networking 构建在线游戏,但我遇到了 Photon.Realtime.Player.SetCustomProperties() 方法的问题。我已经用谷歌搜索过了,但我找不到任何类似我的问题的东西。

关于项目

配对系统没什么特别的:我有一个登录场景(现在没有密码),它将连接到 Photon。当 OnConnectedToMaster 事件发生时,我加载将显示房间的大厅场景。最后,当 OnJoinedRoom 被调用时,我为房间本身加载了第三个场景,它将显示玩家、设置的团队、游戏配置等。

我已经为 Player and Room (RoomInfo) class 进行了扩展 class,以便更轻松地清理 get/set 自定义属性。

问题

一旦加载 Room 场景,我想从 Player 获取一些属性以显示在 Room 中,例如 MMR(排名)。所以我做了以下代码:

public static class PlayerExtensions
{
    private static readonly string _mmrProperty = "mmr";

    public static void SetMmr(this Player player, int mmr)
    {
        player.SetCustomProperties(new Hashtable() { { _mmrProperty, mmr.ToString() } });
    }

    public static int GetMmr(this Player player)
    {
        return (int)player.CustomProperties[_mmrProperty];
    }
}

GetMmr() 上出现空异常错误后,我意识到播放器中没有实际的 'mmr' 自定义 属性。所以我调试了 SetMmr() 并注意到了一些事情:

这是我调试它的 3 个步骤:https://imgur.com/a/YI24dP0

因此,我不确定下一步该怎么做,因为 SetCustomProperties() 似乎不起作用。 有任何想法吗?谢谢。

tl;博士

  • 永远不要直接设置 Player.CustomPropertiesRoom.CustomProperties(将它们用作只读),而是始终使用 SetCustomProperties 方法。
  • 等待 OnPlayerPropertiesUpdate 回调,然后尝试访问您刚刚设置的更新后的 属性 值。

By default, setting properties for actor or room properties will not take effect on the sender/setter client (actor that sets the properties) immediately when joined to an online room unlike what it used to be in PUN Classic. Now, instead, the sender/setter client (actor that sets the properties) will wait for the server event PropertiesChanged to apply/set changes locally. So you need to wait until OnPlayerPropertiesUpdate or OnRoomPropertiesUpdate callbacks are triggered for the local client in order to access them. The new behaviour is due to the introduction of the new room option flag roomOptions.BroadcastPropsChangeToAll which is set to true by default. The reason behind this is that properties can easily go out of synchronization if we set them locally first and then send the request to do so on the server and for other actors in the room. The latter might fail and we may end up with properties of the sender/setter client (actor that sets the properties) different locally from what's on the server or on other clients. If you want to have the old behaviour (set properties locally before sending the request to the server to synchronize them) set roomOptions.BroadcastPropsChangeToAll to false before creating rooms. But we highly recommend against doing this.

source