You should select the players after going through the entire list, so your code referring to chosenplayerone and chosenplayertwo should happen after the for loop ends.
There's two things to keep in mind then. The first is that if you don't have at least two players in the game at this time, your script will error.
Second, the order won't be random! While the order may be in some strange order, every time the script is run (in a relatively close amount of time, i.e., within a few minutes) the order should be the same, so the same two people will be chosen over and over.
You have to either shuffle the list or pick random positions (picking random positions is much easier).
The modifications would look like this:
players = {}
for _,v in pairs (game.Players:GetChildren()) do
table.insert(players, v.Name)
end
chosenplayerone = game.Players:FindFirstChild( players[math.random(1,#players)] );
repeat
chosenplayertwo = game.Players:FindFirstChild( players[math.random(1,#players)] );
until chosenplayertwo ~= chosenplayerone
chosenplayerone.Status.Value = "Vigilante"
chosenplayertwo.Status.Value = "Hero"
Here is another way to do it that doesn't involve the icky repeat until loop:
players = {}
for _,v in pairs (game.Players:GetChildren()) do
table.insert(players, v.Name)
end
local randomIndex = math.random(1,#players) ;
chosenplayerone = game.Players:FindFirstChild( players[randomIndex] );
table.remove(players,randomIndex);
chosenplayertwo = game.Players:FindFirstChild( players[math.random(1,#players)] );
chosenplayerone.Status.Value = "Vigilante"
chosenplayertwo.Status.Value = "Hero"
We can make this still shorter by realizing that game.Players:GetChildren() already stores a list of players! This eliminates the loop as well as the calls to FindFirstChild:
players = game.Players:GetChildren();
local randomIndex = math.random(1,#players);
chosenplayerone = players[randomIndex];
table.remove(players,randomIndex);
chosenplayertwo = players[math.random(1,#players)];
chosenplayerone.Status.Value = "Vigilante"
chosenplayertwo.Status.Value = "Hero"
1 comment
I get the same error on line 5, near random, it says 'bad argument #2 to 'random', interval is empty.