Reward all players

So i want to make a reward system that gives all players gold
Problem is i dont know how i would script this

local playersservice = game:GetService("Players")
local players = playersservice:GetPlayers()
local reward = 30


local function rewardplayers()
for i,v in pairs(players) do
		for count = 1, #players do
			v.leaderstats.Gold.Value = v.leaderstats.Gold.Value + reward
		end
	end
end

i tried something like the one above but it didnt work as in it didnt give the gold, and no error prints
(this is on a serverscript in server script service)

You don’t need the “for count = 1, #players do” part. The first loop will loop through everything in the table (in this case the players), and run code for each thing in the loop. Technically your code should work, it would just give everyone 30 Gold times the amount of players in the game. Maybe you forgot to actually call the function?

local playersservice = game:GetService("Players")
local players = playersservice:GetChildren()
local reward = 30


local function rewardplayers()
       for i,v in pairs(players) do
			v.leaderstats.Gold.Value = v.leaderstats.Gold.Value + reward
       end
end

wait(5)
rewardplayers()
1 Like

I did not forget to call the function and even though i tried your code it did not work. I added some prints to see what was not working

local playersservice = game:GetService("Players")
local players = playersservice:GetChildren()
local reward = 30

local function rewardplayers()
	print("fired") -- this prints
	for i,v in pairs(players) do
		print("gave gold") --this does not print
		v.leaderstats.Gold.Value = v.leaderstats.Gold.Value + reward
	end
end

wait(30)
rewardplayers()

You have to redefine “players” as a local variable inside your function. Since it’s a global at the top of your script, it will only get the current players at the start of the server, not every time you reward the players. Try changing it to this:

local playersservice = game:GetService("Players")
local reward = 30

local function rewardplayers()
    local players = playersservice:GetChildren()
	print("fired") -- this prints
	for i,v in pairs(players) do
		print("gave gold") --this does not print
		v.leaderstats.Gold.Value = v.leaderstats.Gold.Value + reward
	end
end

wait(30)
rewardplayers()
1 Like