My data store isn't working

I am trying to to make my data store work with two values but it doesn’t work here is my script:

local DataStoreService = game:GetService("DataStoreService")
local CustomizationData = DataStoreService:GetDataStore("CustomizationStats")

game.Players.PlayerAdded:Connect(function(Player)
	local Leaderstats = Instance.new("Folder", Player)
	Leaderstats.Name = "leaderstats"
	local Cash = Instance.new("IntValue", Leaderstats)
	Cash.Name = "Cash"
	Cash.Value = 1
	
	local Gems = Instance.new("IntValue", Leaderstats)
	Gems.Name = "Gems"
	Gems.Value = 0
	
	
	
	local playerUserId = "Player_"..Player.UserId
	

	local data = CustomizationData:GetAsync(playerUserId)

	if data then
		Cash.Value = data.Cash
		Gems.Value = data.Gems
	end
	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	
	CustomizationData:SetAsync(playerUserId, {
		player.leaderstats.Cash.Value,
		player.leaderstats.Gems.Value
	
	})

end)

You should wrap your GetAsync method inside of a pcall, as to determine whether or not it’s successful. It should look something like this:

local success, data = pcall(function()
   return CustomizationData:GetAsync(playerUserId)
end)

From here, you can check whether or not it was a success on getting that data. You can use some debugging prints from there to see whether or not the data is being saved correctly. If it isn’t, try to save the data before the player is removed, as it isn’t the safest way to save player data.

1 Like

should be like this when you are saving:

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	
	CustomizationData:SetAsync(playerUserId, {
		Cash = player.leaderstats.Cash.Value,
		Gems = player.leaderstats.Gems.Value
	})

end)

then you can get it by:

Datastore:GetAsync(USERID).Cash
&
Datastore:GetAsync(USERID).Gems

if you are doing it your way then you need to get the table’s arguments instead of the variables:

Cash = data[1] -- Cash
Gems = data[2] -- Gems
1 Like

Wrap all set asyncs and get asyncs in pcalls (as mentioned in Sekonds post)

And make sure in your game settings under security “Enable Studio Access To API Services” if you’re testing in Roblox Studio.

And as above do

Cash = data[1]
Gems = data[2]

To add to the previous posts, you should be using:

https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose

Make sure that when testing, you change the client to the server client. Otherwise, it won’t work in studio.