How do I Make This Datastore Script Load your Data When you Join?

In a few of my games, I use datastores to save progress. The only problem is, in order to load your data, you need to get more of that value (For example, if your kills in a game were saved, you would need to get another kill for the data to load.)

This is the code for my script, in this instance, the value is “Cash”

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStoreValues") --Name the DataStore whatever you want

game.Players.PlayerAdded:Connect(function(player)

	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"

	local Cash = Instance.new('NumberValue', leaderstats)
	Cash.Name = "Cash"
	Cash.Value = 0

	local value1Data = Cash

	local s, e = pcall(function()
		value1Data = DataStore:GetAsync(player.UserId.."-Value1") or 0 --check if they have data, if not it'll be "0"
	end)

	if s then
		Cash.Value = value1Data --setting data if its success
	else
		game:GetService("TestService"):Error(e)  --if not success then we error it to the console
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local s, e = pcall(function()
		DataStore:SetAsync(player.UserId.."-Value1", player.leaderstats.Cash.Value) --setting data
	end)
	if not s then game:GetService("TestService"):Error(e) 
	end
end)

i tested your script and it works perfectly fine, did you perhaps forget to enable this?
image

No, I have this enabled, it just doesn’t load automatically

Basically, I want it to load when you join the game.

so it works and is just very slow?

What you have to do to get it to load is make more of the currency, if you want your money to load, you need to get some money to make it load.

One of the possible solutions for this is to give a player some of the currency (For example, $1,000) and subtract that.

i cant really tell what the problem you are having is

1 Like