i'm making a randomizeTeams() function to randomly but evenly assign players to 2 teams, and i've noticed while, it works, it's not random, choosing the same players over and over to be on the same teams over and over, any ideas how i can make it truly random?
local function randomizeTeams() local players = game.Players:GetPlayers() for i,v in pairs(players) do if i > #players/2 then v.Team = game.Teams.Team1 else v.Team = game.Teams.Team2 end end end
Truly random isn't really achievable... But! For the sake of our purposes here math.random() should do the trick :)
It's been a while since I've done Roblox coding but this and this might be helpful :)
You could loop over each player in the game and generate a random number for each of them, say you have ten players, each would get a random number and then the highest five players will be put into one team and the remaining five would form the other team :)
//This might need a little work, it's a while since I've done lua and I'm typing on mobile //Whenever a round is being set up call "randomiseTeams" local function randomiseTeams() local players = game.GetService("Players") local teams = game.GetService("Teams") local randomiser ={} //will be filled as a dictionary linking a player to a random number local array = [] //to order the dictionary, table.sort isn't meant for dictionaries for _,player in pairs(players) do randomiser[math.random()] = player.name //generates a random number and links it to a player name end for i,_ in pairs(randomiser) do table.insert(array, key) end table.sort(array) for i,number in pairs(array) do if i < array.length/2 then players.FindFirstChild(randomiser[number]).team = //teamOne else players.FindFirstChild(randomiser[number]).team = //teamTwo end end end
It might be a bit complicated but it basically gets all players in the game, puts them in a dictionary with a random number attached to them Then the random numbers get sorted in an array Then this sorted list of random numbers is used to separate the players into teams... Hopefully it works alright, might have some bugs lol