I have been learning studio for the past week or so (very new to it) and I can NOT get my save data to work correctly. For some reason it worked twice but on the third test it no longer worked. What is missing or in the wrong place here? If anyone has any ideas please let me know! and yes, API services are on!

local DataStoreService = game:GetService("DataStoreService")

local CashStore = DataStoreService:GetDataStore("Cash")

local player = game.Players.LocalPlayer

local STARTING_CASH = 100

local function onPlayerAdded(player)

local playerKey = "Player\_" .. player.UserId

print("User ".. player.UserId.. " Joined")

local leaderstats = Instance.new("Folder")

leaderstats.Name = "leaderstats"

leaderstats.Parent = player

local Cash = Instance.new("IntValue")

Cash.Name = "Cash"

Cash.Parent = leaderstats

local myCash

local success, err = pcall(function()
myCash = CashStore:GetAsync(playerKey) or STARTING_CASH

end)

if success then

	Cash.Value = myCash

	print("loading "..myCash)

else

	print("failed to retrieve data")

	warn(err)

end
end

game.Players.PlayerAdded:Connect(onPlayerAdded)

---------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------

local function onPlayerLeft(player)

local playerKey = "Player\_" .. player.UserId

local myCash = player.leaderstats.Cash.Value

print(myCash)

local success, err = pcall(function()

	myCash = CashStore:SetAsync(playerKey, myCash)

end)

	if success then

		print("User "..playerKey.." saved with "..myCash.." in the bank")

	else

		print("error")

		warn(err)

	end
end

game.Players.PlayerRemoving:Connect(onPlayerLeft)

3 comments

0

ignore those slashes on "Player_" idk why those are there

0

https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose specifically, check "saving player data before shutting down" in the code samples section 

0

you need to save the data of anyone that leaves the server using PlayerRemoving, AND when the server shuts down, you need to save the data of everyone in the server using game:BindToClose