Script not working as wanted

I’m trying to make this script give the player 5 coins every minute but it’s coming up with an error saying attempt to index nil with WaitForChild

local Players = game:GetService("Players")
local player = Players.LocalPlayer

while true do
	wait(60)
	player:WaitForChild("leaderstats").Coins.Value += 5
end
1 Like

You are perhaps accessing LocalPlayer through a server script? It’s not possible, you either had to:

  1. WaitForChild your player (works for once player only)
  2. Loop through all players:
while true do
	task.wait(60)
	for _, v in ipairs(Players:GetChildren()) do
		local Stats = player:FindFirstChild("leaderstats")
		
		if Stats then
			Stats.Coins.Value += 1
		end
	end
end

Make Script in ServerScriptService
Code:

local CoolTime = 60
local amount = 5
while wait(CoolTime) do
   for_, v in pairs(game.Players:GetPlayers()) do
 v.leaderstats.Value += amount
end

Why don’t you use game.Players:GetPlayers()?

Can’t you do this simply

game.Players.PlayerAdded:Connect(function(player)
  while true do
    task.wait(60)

    local cash = player:WaitForChild("leaderstats").Coins.Value
    cash = cash + 5 
  end
end)
1 Like

this is best.

local CoolTime = 60
local amount = 5
while wait(CoolTime) do
   for_, v in pairs(game.Players:GetPlayers()) do
 v.leaderstats.Value += amount
end
1 Like

I never knew this existed, although the results should be the same 99% of the time.

Hey! Put this in a server script under ServerScriptService, it’ll do what you want to do!

You can change WAITS_BETWEEN_REWARD to how long you want to wait before rewarding each player.
You can change COINS_TO_REWARD to how many coins you want to reward each player.

This code snippet will reward 5 coins every 60 seconds.

local WAIT_BETWEEN_REWARD = 60 -- seconds you want to wait before giving a coin
local COINS_TO_REWARD = 5 -- how many coins you want to reward every WAIT_BETWEEN_REWARD seconds

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local timeElapsed: number = 0

RunService.Heartbeat:Connect(function(deltaTime: number)
    timeElapsed += deltaTime

    if timeElapsed >= WAIT_BETWEEN_REWARD then
        timeElapsed = 0

        for _, player: Player in ipairs(Players:GetPlayers()) do 
            local leaderstats: Folder | Model? = player:FindFirstChild("leaderstats")
            local coinValue: IntValue? = leaderstats and leaderstats:FindFirstChild("Coins")

            if not coinValue then
                return
            end

            coinValue.Value += COINS_TO_REWARD
        end
    end
end)
2 Likes