Script to add money every second

I’m trying to make a script that detects when a new player has joined the game and immediately starts giving them money every second. This is what I have so far:

game.Players.PlayerAdded:Connect(function(plr)
	local cash = plr.leaderstats.Cash.Value
	while true do
		cash = cash + 1
		wait (1)
	end
end)

However, when the game starts this error is produced:

I can’t understand why this is happening, leaderstats is working fine and shows perfectly. It’s also set up with datastores.

2 Likes

leaderstats is a folder you have to create yourself and add to the player.

Are you sure you create the leaderstats before the code is run? Try add this code at the bottom of where the leaderstats get created or use the :WaitForChild() to wait for the leaderstats to be made.

Have you Created a folder called leaderstats? If no then

Create a folder called leaderstats then add IntValue in the folder that you created

The user stated in the main post saying that “leaderstats is working fine and shows perfectly” which means this cannot be the issue because they clearly know that it has been created. No need to explain what leaderstats are.

It’s possible this code is running before leaderstats has been even created then. Just make a check to ensure it actually exists using :WaitForChild().

Sorry, just not used to this way of coding relying on while true do loops requiring you to break code up code, was just assuming leaderstats would have been all managed in a single script.

wait until leaderstats exist probably

game.Players.PlayerAdded:Connect(function(plr)
	local cash = plr:WaitForChild("leaderstats", math.huge):WaitForChild("Cash", math.huge)
	while true do
		cash.Value = cash.Value + 1
		wait (1)
	end
end)
3 Likes

I did create leaderstats already… I did say this

Yes I do, as I said it’s working fine and is saving too.

Yes sorry, didn’t read full post. Just use :WaitForChild() to make sure the game has time to create leaderstats folder.

I just assumed the folder would be created on a PlayerAdded event trigger.

Thanks, completely overlooked that the script might have run before the leaderstats one.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.