SetAsync() DIRECTLY sets the value and the old value will be lost. However, there is a function called UpdateAsync(). This function "transforms" the old value into a new one. Here is an example:
This script adds 10 coins to the player's data upon leaving.
local dss = game:GetService("DataStoreService"):GetDataStore("Coins")
game.Players.PlayerRemoving:Connect(function(plr)
local key = "Plr-"..plr.UseId
dss:UpdateAsync(key, function(oldValue)
local newValue = oldValue or 0
return newValue + 10
end)
end
Using UpdateAsync() is okay when you are going to use the OldValue for updating or doing anything upon updating. However, there is a shorter way ONLY when the data value is an integer.
And the way is to use IncrementAsync()!
Using the code from above, let's do this the easiest way!
local dss = game:GetService("DataStoreService"):GetDataStore("Coins")
game.Players.PlayerRemoving:Connect(function(plr)
local key = "Plr-"..plr.UseId
dss:IncrementAsync(key, 10)
end
These two methods are very good ways to update your data! Also, If you wanted to organize you data storage, there is a second parameter named scope which has a default value of global. It is like an organizer that belongs to the same category.
For example, local dss = game:GetService("DataStoreService"):GetDataStore("Coins")
IS NOT THE SAME AS
local dss = game:GetService("DataStoreService"):GetDataStore("Coins", "Silver")
They are different because their SCOPES are different! That's how you can store different types of data in a datastore. Make sure to reference the Scope in the dss variable (script above) so you can also GetAsync from it.
Don't forget that there are limits applied to saving data, so make sure that the game does not try to update data too often, or else you will be flooded with request rejected errors!
That's all I can tell you about Data Stores. If you have any questions, please comment below. Thanks and have a nice day!
1 comment
https://scriptinghelpers.org/questions/27426/how-to-use-datastores#30949