Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I randomly select players to join a certain team?

I've made a script here that other people actually helped me on, I was just wondering how to use the math.random function to randomly select players to join the other team. Here's what I have so far.

local ms = Instance.new("Message")
ms.Parent = workspace
ms.Text = "Welcome to my testing place!"
wait(5)
ms.Text = "In 5 seconds you will be moved to a map."
wait(5)
ms.Text = "You have entered the map."
for index, player in pairs(game:GetService("Players"):GetPlayers()) do
    player.TeamColor = BrickColor.new("Bright red")
	player.Character.Humanoid.Health = 0
end
wait(5)
ms:Destroy()

1 comment

0

players[math.random(1, #players)]?

1 answer

Random function


The math.random function , when given a lower bound and an upper bound, generates a pseudo-random integer between the two numbers, for example:

math.random(1,10)--7 (just an example, it isn't always 7)

If they math.random function isn't given any parameters, it generates a number between 0 (inclusive), and 1(exclusive)

Ex.

math.random() --0.84018771676347

Seeds

you can make a pseudo random number generation function more.... well, random, is by giving it a seed using a math.randomseed() function

math.randomseed(tick())


A better alternative


A better alternative the math.random , would be the NextInteger and NextNumber functions of the random library.

An example would be:

local rand = Random.new(tick())--similar to math.randomseed(tick()), except it isnt global per se

print(rand:NextInteger(1,10))--7
print(rand:NextNumber())--0.84018771676347

As you can see, the random library is similar to the math library's random functions, however, you can check out EmilyBendsSpace's answer here to note some of the key differences


Application


With all that said, here is an example of how it could be applied to your code.

local teamName = "TeamName"
local rand = Random.new(tick())
for index, player in pairs(game:GetService("Players"):GetPlayers()) do
	local rn = rand:NextNumber()
	if rn > 0.5 then
		player.Team = game.Teams[teamName]
		player.Character.Humanoid.Health = 0
	else
		....
	end
end

Now obviously this isn't a complete script, but rather just an example, some of the things here that I did were just to avoid confusion such as the teamName variable

Hopefully this helped!

This discussion is preserved as it was. New answers, comments, and votes are closed.