So today I read up on Data Store and watched some videos on Youtube. I made a script using PeasFactory's tutorial on Youtube and I am wondering why it isn't working for my game? I have altered the values to suit my needs, but I think in doing so I messed it up and I cannot find what is wrong. I want the script to save 'SpiritCoins' (being the currency of my game) and 'Survivals' (the number of times people survive my disasters/minigames).

local DataStore = game:GetService("DataStoreService"):GetDataStore("SpiritCoinsAndSurvivals")

game.Players.PlayerAdded:connect(function(player)
	
	local stats = Instance.new("IntValue", player)
	stats.Name = "leaderstats"
	
	local coins = Instance.new("IntValue", player)
	coins.Name = "SpiritCoins"
	
	local survivals = Instance.new("IntValue", player)
	survivals.Name = "Survivals"
	
	local key = "player-"..player.userId
	
	local savedValues = DataStore:GetAsync(key)
	
	if savedValues then
		--Save format: {coins, survivals}
		coins.Value = savedValues[1]
		survivals.Value = savedValues[2]
	else
		local valuesToSave = {coins.Value, survivals.Value}
		DataStore:SetAsync(key, valuesToSave)
	end
end)

And here is the script for when the player leaves the game so it saves the data.

local DataStore = game:GetService("DataStoreService"):GetDataStore("SpiritCoinsAndSurvivals")

game.Players.PlayerRemoving:connect(function(player)
	
	local key = "player-"..player.userId
	
	--Save key: {coins, survivals}
	local valuesToSave = {player.leaderstats.SpiritCoins.Value, player.leaderstats.Survivals.Value}
	DataStore:SetAsync(key, valuesToSave)
	
end)

Though I have read on the wiki an UpdateAsync is a good thing to have. I will need to learn about that and add it to the leaving script. If there is anything I left out, please don't hesitate and keep in mind I am still a beginner level scripter.

4 comments

0

Your script looks perfectly fine. The only problem that I could think of is that you might be using these in a local script. DataStores are restricted to server script access only, so make sure that isn't the problem.

0

UpdateAsync is only useful if you care about the previous value. However, it's possible for the datastores to be "down"/malfunction (which causes an error in GetAsync), which means that they will fail to return the user's information. In this case, you should periodically try again until you're successful (ex every 10 seconds) - and don't save to someone's datastore until the request has succeeded

0

It is in a regular script. When the 2 scripts are in my game it doesnt show the values in the leaderboards at all. Plus, the game lags severly for 7 seconds once it chooses the map with the scripts in as well. Any ideas?

0

I FIXED IT! I accidentally put 'player' where 'stats' should have been in the first script for the IntValues. Thank you guys for looking it over though.