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

Player data for "leaderstats" won't save on my world, anyone know a fix?

local DSServ = game:GetService("DataStoreService")
local plrServ = DSServ:GetDataStore("PlrLeaderboard")

game.Players.PlayerAdded:Connect(function(client)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats" 
	leaderstats.Parent = client
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash" 
	cash.Parent = leaderstats 
	
end)

game.Players.PlayerRemoving:Connect(function(client)
	local userId = client.UserId 
	if userId == 316061618 then 
		print("THE OWNER IS HERE!")
		client.leaderstats.Cash.Value = client.leaderstats.Cash.Value + 1000
	end
	local success, errorMessage = pcall(function()
		plrServ:SetAsync(client.UserId.."-cash", client.leaderstats.Cash.Value)
	end)
	
	if success then 
		print("Successfully saved data!")
	else 
		print("An error occured attempting to save data")
		warn(errorMessage)
	end
end)

This may seem like a lot, but I'm just trying to save player data to set up a currency system for a game (the world has API for Studio turned on). I made a mechanic that adds 1000 to my currency whenever I leave the game (it checks for my UserId and adds it if the current player's Id and mine match, meaning it's me). I don't know what the problem is, but it won't save the data. Please let me know what the problem is if you think you know. Thx

1 comment

0

Maybe you don't load it once you join?

1 answer

✓ Accepted answer
local DataStore = game:GetService("DataStoreService")
local CashData = DataStore:GetOrderedDataStore("Cash")

game.Players.PlayerAdded:Connect(function(plr)
	local Cash = CashData:GetAsync(plr.UserId) 
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	local CashValue = Instance.new("IntValue", leaderstats)
	CashValue.Value = Cash
	leaderstats.Parent = plr
	CashValue.Name = "Cash"
	
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local Cash = plr.leaderstats.Cash.Value
	CashData:SetAsync(plr.UserId,Cash)
	print("Saved data")
end)

--you can change anything called Cash to your currency

3 comments

0

on line 8, what does the 2nd parameter do?

0

Thanks, the script worked! Btw could you explain how this all works. Do it only if you want to, just wanting to know that I understand what the code is doing.

0

Line 8 is just for me. It for a different script. Forgot to take that out

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