I'm making a round-based game and I'm adding every player to a table to get easy access to them but only one player gets in a table, Can anyone tell me why?
Here's the code to add them to the table
1 | local playersAlive = { } |
2 |
3 | for i, player in pairs (game.Players:GetPlayers()) do |
4 | if player then |
5 | table.insert(playersAlive, player) |
6 | end |
7 | end |
I’m bad at scripting but I think you can try to delete the if loop and see if it works
Can you not do, I haven't tried it but it should work in theory
1 | local playersAlive = game.Players:GetPlayers() |
What I would do is to put the for loop inside a while true loop, here's what I think will work
01 | local playersAlive = { } |
02 |
03 | while true do |
04 | wait() |
05 | for i, player in pairs (game.Players:GetPlayers()) do |
06 | if player then |
07 | table.insert(playersAlive, player) |
08 | end |
09 | end |
10 | end |
11 |
12 | --btw i prob would recommend you do local playersAlive = game.Players:GetChildren() since this would just be easier instead of doing this loop |
This should be working. You weren't supplying all the parameters necessary for table.insert
1 | local playersAlive = { } |
2 |
3 | for i, player in pairs (game.Players:GetPlayers()) do |
4 | if player then |
5 | table.insert(playersAlive,#playersAlive+ 1 , player) |
6 | end |
7 | end |
The second parameter is where you put the thing within the table. This will automatically set the index to the tables length +1
By the way you don't need to include the if statement, it's just useless in this case.
Plus I'd personally use collection service Instead of manually adding and removing players from the players alive table, but it doesnt matter, it's just my preference
prints playersAlive table, updates every 10 seconds
01 | local Players = game:GetService( "Players" ) |
02 | local playersAlive = { } |
03 |
04 | local function onPlayerAddToTable(player) |
05 | table.insert(playersAlive, "User: " .. player.Name) |
06 | print ( "worked" ) |
07 | end |
08 |
09 | for _, player in pairs (Players:GetPlayers()) do |
10 | onPlayerAddToTable(player) |
11 | end |
12 | Players.PlayerAdded:Connect(onPlayerAddToTable) |
13 |
14 | while true do |
15 | wait( 10 ) |
16 | print (playersAlive) |
17 | end |
18 |
19 | --dont care if the code output is messy it works ok bye |
20 | --by piximentility |