I know there are a lot of topics on here about finding the amount of players in a server, but what I want is to use the amount of players and change the amount of cash being distributed among the players depending on how many players are in the server. Right now, for my game, I have a round system, and at the end of the round players get Gold. I decided that I wanted the gold to be divided by the amount of players in the server to make the game more fair, and I haven’t done any scripting with this specific stuff before, so I’m unsure how to do that. I do have some script and it’s returning no errors. I will attach that below.
local numberOfPlayers = #Players:GetPlayers()
^
This is where I got the number of players (I’m guessing this is where the issue is)
local reward = 50 * wave
for i, player in ipairs(Players:GetPlayers()) do
player.Gold.Value += reward / numberOfPlayers
print("There are " .. numberOfPlayers .. " players in the server")
^
This is where I actually used the number of players and divided the reward among the players. Also, it’s printing out that I have 0 players in the server, even though I do have players in the server, which is why I don’t think this part of script is where the issue is coming from.
If this was placed somewhere like at the top of the script, is not inside of any functions, and is not updated at any other point, its value will be the same as when the script first started up.
To resolve that, consider updating the variable right before the loop, like so:
local numberOfPlayers = #Players:GetPlayers() -- This can continue to be kept whereever it was if it needs to be accessed outside of the scope where the loop is
...
local reward = 50 * wave
numberOfPlayers = #Players:GetPlayers() -- Updates the variable with the current value returned by #Players:GetPlayers()
for i, player in ipairs(Players:GetPlayers()) do
player.Gold.Value += reward / numberOfPlayers
-- Continue
If you want to get the number of players.
You can try this. It updates automatically too!
Edit: I meant to reply to the first guy.
local numberOfPlayers = 0 --This is current players.
game.Players.PlayerAdded:Connect(function()
numberOfPlayers += 1 --Adds a player when they join.
end)
game.Players.PlayerRemoving:Connect(function()
numberOfPlayers -= 1 --Removes a player when they leave.
end)
local reward = 50 * wave --I don't know what waves means, but it should be fine.
for i, player in ipairs(Players:GetPlayers()) do
player.Gold.Value += reward / numberOfPlayers
print("There are " .. numberOfPlayers .. " players in the server")
end