PUN 2 获取自定义属性

PUN 2 Getting Custom Properties

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

来自 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
    }

来自玩家控制器:

[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)的玩家被选为 "angel"。这里的检查是必要的,因为在多个天使的情况下,你不希望一个已经存在的天使算作一个新的变化。 (此外,如果我要使用自定义属性,通常了解如何获取它们可能很重要。)如果我不在 RoundSystem 中包含检查,结果是 2 个公民和 1 个天使(在 3 个测试中玩家)。此外,如果您看到任何可以改进的意大利面条代码,请不要犹豫告诉我。 :)

使用 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