i am trying to make a random player select for my murder mystery game.
But once it tries to do the math.random(1,#v) - v is for players:GetChildren(), the output gives me an error that says "attempt to get length of an instance value"
here is my script:
1 | for _, v in pairs (game.Players:GetChildren()) do |
2 | local randomSelect = math.random( 1 ,#v) |
3 | if v ~ = v [ randomSelect ] then |
4 | revealRoleRemote:FireClient(v, "Normal" ) |
5 | else |
6 | revealRoleRemote:FireClient(v, "Murder" ) |
7 | end |
8 | end |
Please help me out!
It's because you are looping through the list of players making v
the actual player object.
You should get the list of players and access the table with a random number:
1 | local players = game.Players:GetPlayers() -- list of players |
2 |
3 | local randomPlayer = players [ math.random( 1 , #players) ] |
4 | --see how "players" is a list and we index with a random number |
5 | --from 1 to the list's length, giving us a random player! |
This should work
1 | for _, v in pairs (game.Players:GetPlayers()) do |
2 | local randomSelect = math.random( 1 ,#game.Players:GetPlayers()) |
3 | if v ~ = game.Players [ randomSelect ] then |
4 | revealRoleRemote:FireClient(v, "Normal" ) |
5 | else |
6 | revealRoleRemote:FireClient(v, "Murder" ) |
7 | end |
8 | end |