Random character selection not working

Hi, I am trying to have a function loop through all of the players and give them a character to play as, but it’s not working. Here is my script:

function module.DressPlayers()
	for i, player in pairs(game.Players:GetPlayers()) do
		if player.Character then
			for _, character in pairs(game.ReplicatedStorage.PlayableCharacters:GetChildren()) do
				local random = Random.new()
				local characters = game.ReplicatedStorage.PlayableCharacters:GetChildren()
				local chosenCharacter = characters[random:NextInteger(1,#characters)]
				chosenCharacter.Name = player.Name
				player.Character = chosenCharacter
				chosenCharacter.Parent = workspace
			end
		end
	end
end

The error seems to have gone away, however this only works on one player and works once…

have you tried math.random([min],[max])?

1 Like

It seems to be working, though it doesn’t loop through everyone oddly…

Does it work on everyone currently in the server? Is it meant to work on people who join after the code runs? I have to go now

It supposed to work on everyone who is in the server, not people afterwards.

It is working! I figured out the issue. Here is my working code:

function module.DressPlayers()
	for i, player in pairs(game.Players:GetPlayers()) do
		if player.Character then
			local random = Random.new()
			local characters = game.ReplicatedStorage.PlayableCharacters:GetChildren()
			local chosenCharacter = characters[random:NextInteger(1,#characters)]
			chosenCharacter.Name = player.Name
			player.Character = chosenCharacter
			chosenCharacter.Parent = workspace
		end
	end
end

Not anymore, it seems that it only works once then an error occurs at this line

To add to this, is there anyway to detect if a player is the same character as someone else?