Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make my Datastore load the player's Cash?

Script so when the player joins the game, it gives the leaderstats folder + the Cash value inside

function onPlayerEntered(newPlayer)
	wait()
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"

	local score = Instance.new("IntValue")
	
	score.Name = "Cash"
	score.Value = 0

	score.Parent = stats	
	stats.Parent = newPlayer
end

game.Players.ChildAdded:connect(onPlayerEntered)

Datastore Script

local ds = game:GetService("DataStoreService"):GetDataStore("CashData")

game.Players.PlayerAdded:Connect(function(plr) --Load
	
	wait(0.2)
	
	local plrkey = "id_"..plr.userId
	local leaderstats = plr:WaitForChild("leaderstats")
	local cash = leaderstats:WaitForChild("Cash")
	
	local GetSaved = ds:GetAsync(plrkey)
	
	if GetSaved then
		cash.Value = GetSaved[1]
	else
		local NumberForSaving = {cash.Value}
		ds:GetAsync(plrkey, NumberForSaving)
	end
	
	while wait(300) do --AutoSave
		ds:SetAsync("id_"..plr.userId, {plr.leaderstats.Cash.Value})
	end
end)

game.Players.PlayerRemoving:Connect(function(plr) --Save
	local leaderstats = plr:WaitForChild("leaderstats")
	local cash = leaderstats:WaitForChild("Cash")
	ds:SetAsync("id_"..plr.userId, {cash.Value})
end)

[Error is from the Datastore script]:

"ServerScriptService.CashDatastore:14: attempt to index number with number"

1 answer

Not sure if that's the problem, but line 17 (data store script) contains GetAsync(), and it seems like you want to save, not load, so change it to SetAsync(). That might be the problem (No data). But I am not sure since you get Attempt to index number with number, and not nil.

This discussion is preserved as it was. New answers, comments, and votes are closed.