Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

help with math.random()?

Asked by 10 years ago
game.Players.PlayerAdded:connect(function(player)
    local teams = {"Lime green","New Yeller"}
    local num = 1
    player.TeamColor = BrickColor.new(math.random(teams))
end)

I am trying to get people who join after a game has started a team so they dont have to wait for the next round. Anyone got ideas?

2 answers

Log in to vote
2
Answered by
duckwit 1404 Moderation Voter
10 years ago

You need the unary # length operator before your table. The length operator returns the number of elements in an ordered list, and math.random() requires a number, not a table.

You would use it like this:

game.Players.PlayerAdded:connect(function(player)
    local teams = {"Lime green", "New Yeller"}
    player.TeamColor = BrickColor.new(math.random(#teams))
end)
Ad
Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

There is an error in duckwit's code. BrickColor.new() requires a string, but math.random() returns a number. We must get a random object from a table with the form of table[int]. Putting a number in the brackets will give you the value from the table that corresponds with that number. Since math.random() returns a number, we're good to go.

player.TeamColor = BrickColor.new(teams[math.random(#teams)] )


I would like to point out, however, that this is unnecessary! Roblox provides an AutoAssignable property of Teams that will automatically assign and balance teams. Everyone player who joins will be assigned a team. This is also a better method, for it makes it impossible (except with an odd number) for teams to be unbalanced.

Answer this question