Datastore error

Hey, I’m trying to make it so my in-game points save with this datastore script but it is erroring and I don’t know why

local DataStoreService = game:GetService(“DataStoreService”)
local myDataStore = DataStoreService:GetDataStore(“myDataStore”)

game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new(“Folder”)
leaderstats.Name = “leaderstats”
leaderstats.Parent = plr

local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Value = 0
cash.Parent = leaderstats

local strength = Instance.new("IntValue")
strength.Name = "Strength"
strength.Value = 0
strength.Parent = leaderstats

local data
local success, errormessage = pcall(function()
	data = myDataStore:GetAsync(plr.UserId.."-cash")
end)

if success then
	cash.Value = data
else
	print("There was an error when saving your data")
	warn(errormessage)
end

end)

game.Players.PlayerRemoving:Connect(function(plr)
myDataStore:SetAsync(plr.UserId…“-cash”,plr.leaderstats.Cash.Value)
end)

if success then
print(“Player data successfully saved!”)
else
print(“There was ana error when saving your data”)
warn(errormessage)
end

  1. What’s the error?
  2. Could you please put 3 ` at the start and end of your code block so its properly formatted.
1 Like

Well, did you enable access to API services in game settings? You need to do that. Also, you need to test the datastores outside of studio since they won’t work inside of it.

1 Like

It’s showing the blue line under success and errormessage even though I made them a variable

You’d have to make another pcall(function() under PlayerRemoving statement, as you only provided one that’s accessible under PlayerAdded.

I’d also recommend you putting :BindToClose() function when saving a value, to prevent data loss as the game may shut down before it actually saves the value for the last player that’s leaving.

Where does it error?