What is wrong with my money giving script?

Hello Developers! I am trying to make it so it gives you 1 playtime per second. It worked, but then it said something like "attempt to index nil with ‘FindFirstChild’. " It had previously worked but I just don’t know why it’s not working now.

Here is my script:

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	local Playtime = leaderstats:FindFirstChild("Playtime")
	
	while true do
		wait(1)
		Playtime.Value = Playtime.Value + 1
	end
end)

and here’s the script that creates the values:

local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("MyDataStore") 

local function saveData(player)

	local tableToSave = {
		player.leaderstats.Playtime.Value
	}

	local success, err = pcall(function()
		dataStore:SetAsync(player.UserId, tableToSave) 
	end)

	if success then 
		print("Data has been saved!")
	else
		print("Data hasn't been saved!")
		warn(err)		
	end
end

game.Players.PlayerAdded:Connect(function(player)

	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local Playtime = Instance.new("IntValue")
	Playtime.Name = "Playtime"
	Playtime.Parent = leaderstats

	local data 
	local success, err = pcall(function()

		data = dataStore:GetAsync(player.UserId) 

	end)

	if success then

		Playtime.Value = data[1]

	else 
		print("The player has no data!")
	end

end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, err  = pcall(function()
		saveData(player) 
	end)

	if success then
		print("Data has been saved")
	else
		print("Data has not been saved!")
	end
end)

game:BindToClose(function()
	for _, player in pairs(game.Players:GetPlayers()) do 
		local success, err  = pcall(function()
			saveData(player) 
		end)

		if success then
			print("Data has been saved")
		else
			print("Data has not been saved!")
			error(err)
		end
	end
end)

Thanks in advance to anyone who helps me!

2 Likes

Have you tried using WaitForChild() instead of FindFirstChild()?

1 Like

And that would be changing which script?

If you are creating these things in the other script you should use WaitForChild()

1 Like

The first leaderstats one. Basically what is happening is that you are trying to find the leaderstats folder and the playtime value thing but it hasn’t loaded yet. You have to use waitforchild so the script waits for it to load.

2 Likes

Thanks to both of you! It’s working now!

1 Like