How to have players join teams and auto-balance them?

LethnLethn
I'm just generally checking out and learning all the code to do with PUN, the PhotoNetwork.SetTeam function is pretty self-explanatory but I'd like to know how to do auto-balancing for obvious reasons if I decide to get more people playing the game.

It would also be really nice if I could find out how to create my own custom teams perhaps? The blue team and red team commands work fine if you're making a simple game with two teams on each side but if you're looking for something more complex I'm not sure how to deal with that.

Comments

  • S_OliverS_Oliver ✭✭
    Hi, you can simply add another Team by add another value To the enum, check the Team script. Autobalance ia pretty easy you just need to keep track of asign Player per Team and asign a new player to the smallerTeam. I can post a snippet later this day if needed
  • LethnLethn
    edited May 14
    Oh I see, I do they have example scripts already? I'll check them out, yes a code snippet for the auto-balance would be helpful, thanks.
  • S_OliverS_Oliver ✭✭
    edited May 15
    replace *TeamEnum* with your Enum wich stores your Teams

    //Needed to get the Lenght of your Enum
    Array enumVals = Enum.GetValues(typeof(*TeamEnum*));
    //Pick a Random Number = Random Team
    *TeamEnum * randomTeam = (*TeamEnum *)UnityEngine.Random.Range(0, enumVals.Length);

    //round down for odd maxPlayer settings in Room
    int maxTeamSize = Mathf.CeilToInt(PhotonNetwork.room.MaxPlayers / 2);

    //playersPerTeam is a Dictionary wich stores all players of all Teams
    //Player assign just to a Random Team
    if (Teams.playersPerTeam[randomTeam].Count < maxTeamSize)
    {
    AssignPlayerToTeam(randomTeam, player);
    }

    //Loop thorugh all Teams and check wich Team has the lowest member count
    //and assign to this Team
    for (int i = 1; i < enumVals.Length; i++)
    {
    if (Teams.playersPerTeam[(*TeamEnum *)i].Count < maxTeamSize)
    {
    print((*TeamEnum *)i);
    AssignPlayerToTeam((*TeamEnum *)i, player);
    return;
    }
    }



    private void AssignPlayerToTeam(*TeamEnum* team,PhotonPlayer player)
    {
    player.SetTeam(team);
    Teams.playersPerTeam[team].Add(player);
    }
    I think Photons Team Script already got a DIcitionary to store team members so you dont need to create one.
    Use this as an Example dont just copy and paste it, not tested^^
  • LethnLethn
    edited May 21
    I should check this forum more I didn't think it was very active at first, sorry for the late response, this code is very helpful, thanks! If I make a multiplayer game in the future I at least want to do a better job than Rockstar Studios which is why I was asking about autobalance lol -_- last thing you'd want is to hop into a brand new FPS or something only to find a whole team stacked against you and there wasn't much documentation on this.
Sign In or Register to comment.