首页 > 解决方案 > 加载新场景后 Unity Photon Network CustomPropeties 未更新

问题描述

我正在使用 Photon PUN 在 Unity 上开发在线多人游戏,但房间 CustomProperties 有问题。

在原始大厅屏幕中,当我更改房间属性时,它会为所有玩家更新,但是当我开始游戏时,加载新关卡时,我想使用 CustomProperties 以便 MasterClient 可以为所有玩家设置相同的开始时间。我正在从附加到 DoNotDestroyOnLoad GameObject 的 Game Settings 类和以下 getter/setter 中设置/获取自定义属性:

private static T GetProperty<T>(string key, T deafult)
{
    if (PhotonNetwork.CurrentRoom.CustomProperties.TryGetValue(key, out object value))
    {
        return (T)value;
    }
    else return deafult;
}

private static void SetProperty(string key, object value)
{
    ExitGames.Client.Photon.Hashtable table = PhotonNetwork.CurrentRoom.CustomProperties;
    if (table.ContainsKey(key))
    {
        table[key] = value;
    }
    else
    {
        table.Add(key, value);
    }
}

当我加载新场景时,之前的 CustomProperties 保持不变,新的变化出现在本地但不会出现在其他玩家身上。我曾尝试使用 OnRoomPropertiesUpdate() 但在加载新场景后它没有激活。是否还有其他需要附加到 DoNotDestroyOnLoad 对象的东西?

标签: c#unity3dphoton

解决方案


更改表后,您必须通过重新分配它,SetCustomProperties否则您只是更改本地副本。

private static void SetProperty(string key, object value)
{
    ExitGames.Client.Photon.Hashtable table = PhotonNetwork.CurrentRoom.CustomProperties;
    
    // No need to check Contains
    // This will either Add a new key or overwrite an existing one
    // -> This is more efficient and already behaves exactly the same ;)
    table[key] = value;

    PhotonNetwork.CurrentRoom.SetCustomProperties(table);
}

推荐阅读