【问题标题】:PUN 2 Getting Custom PropertiesPUN 2 获取自定义属性
【发布时间】:2020-04-22 12:22:44
【问题描述】:

我最近承担了 Photon 中自定义属性的任务。我已经能够弄清楚如何设置自定义属性,但不能获取自定义属性。我的哈希表在我的播放器控制器脚本中,而我设置(以及我想要获取)属性的位置在循环脚本中。

来自 RoundSystem:

private IEnumerator TeamBalance()
    {
        angelCount = Mathf.Floor(PhotonNetwork.PlayerList.Length * angelPercent);
        currentAngels = angelCount;
        currentPlayers = PhotonNetwork.PlayerList.Length;

        foreach (var item in PhotonNetwork.PlayerList)
        {
            var itemPhotonView = (PhotonView)item.TagObject;

            itemPhotonView.RPC("SetPlayerTeam", item, citiString);
        }

        for (int i = 0; i < angelCount;)
        {
            var item = PhotonNetwork.PlayerList[Random.Range(0, PhotonNetwork.PlayerList.Length)];
            var itemPhotonView = (PhotonView)item.TagObject;

            if (/* random player selected's, AKA, item's team == citiString */)
            {
                itemPhotonView.RPC("SetPlayerTeam", item, angelString);

                i++;
            }
        }

        yield return null;
        //the reason this is in an IEnumerator with 'yield return null'
        //is because I plan to add a waiting period once I figure this out
        //it's for the game loop
    }

来自 PlayerController:

[PunRPC]
        public void SetPlayerTeam(string teamString)
        {
            //in the class:     private ExitGames.Client.Photon.Hashtable playerProperties; 
            if (!playerProperties.ContainsKey("team"))
            {
                playerProperties.Add("team", teamString);
            }
            playerProperties["team"] = teamString;
            PhotonNetwork.LocalPlayer.SetCustomProperties(playerProperties);
        }

在回合开始时,一定比例(在本例中为 1/3)的玩家被选为“天使”。此处的检查是必要的,因为在多个天使的情况下,您不希望已经存在的天使算作新的变化。 (此外,如果我要使用自定义属性,一般了解如何获取自定义属性可能很重要。)如果我不包括 RoundSystem 中的检查,结果是 2 个公民和 1 个天使(在 3球员)。此外,如果您看到任何可以改进的意大利面条代码,请不要犹豫告诉我。 :)

【问题讨论】:

    标签: c# unity3d multiplayer photon custom-properties


    【解决方案1】:

    使用Player.CustomProperties 字典访问播放器的自定义属性。

        foreach (var item in PhotonNetwork.PlayerList)
        {
            if (item.CustomProperties.ContainsKey("team"))
            {
                Debug.Log(item.CustomProperties["team"]);
            }
        }
    

    此外,RoundSystem 可以实现 IInRoomCallbacks 接口并监听 OnPlayerPropertiesUpdate 以捕捉团队更新的确切时刻。 https://doc-api.photonengine.com/en/pun/v2/interface_photon_1_1_realtime_1_1_i_in_room_callbacks.html

    【讨论】:

    • 谢谢!我确定我已经尝试过了,但我想我错了...另外,感谢您提供有关 OnPlayerPropertiesUpdate 的提示
    • 在一个客户端上更新属性后,您可能需要稍等片刻才能将更改传播到其他客户端
    • 是的,这是我不久后意识到的另一个问题,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2012-05-30
    • 2013-05-30
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多