Answered by
3 years ago Edited 3 years ago
Be sure to enable access to API service in game settings..
You can use the datastoreservice
https://developer.roblox.com/en-us/articles/Data-store
There are two basic methods.
:GetAsync which grab data from a given key
:SetAsync which stores data with a given key and given value
Let me explain what it does
These two methods work on a datastore we create.
By doing that, we do
1 | local dss = game:GetService( 'DataStoreService' ) |
2 | local store = DataStoreService:GetDataStore( "NameYourDataStore" ) |
We got the stats 'Rings'
And we got the event player added which fires when a player joins.
We can use GetAsync to get the data for the player's stat. If the player is new, the getasync that fires won't return data since setasync didn't fire when they left.
But wait, I didn't put setasync or getasync to an example.
What is a key?
A key is a way to access your data.
Setasync has two args. (A Key, A value to store)
While getasync only has one args which is the key because it gets just the value by the key and returns the value associated with the key.
1 | game.Players.PlayerAdded:connect( function (player) |
2 | local fold = Instance.new( "Folder" , player) |
3 | fold.Name = "leaderstats" |
4 | local stat = Instance.new( "IntValue" , fold) |
6 | stat.Value = store:GetAsync(player.UserId) or 0 |
Now it's time for setasync!
We can use it when a player leaves to save the player's stat.
We can do any key such as the player name or player id but it's recommended for the player id because the player can change the username.
You can also do (player.UserId..'Rings') but then we need to change getasync to player.UserId..'Rings' but it's up to you for the key but make sure you get the key properly when getting data.
01 | game.Players.PlayerRemoving:Connect( function (player) |
02 | local success, err = pcall ( function () |
03 | store:SetAsync(player.UserId,player.leaderstats.Rings.Value) |
Now we saved the player's data by using the userid as the key and the rings value. But again, you can also do player.UserId..'Rings' or anything.
But why is there a pcall function?
It is to check if the data save successfully. If not, we can check if there is an error by printing it.
Now you're done!
Full Script:
01 | local dss = game:GetService( 'DataStoreService' ) |
02 | local store = DataStoreService:GetDataStore( "NameYourDataStore" ) |
04 | game.Players.PlayerAdded:connect( function (player) |
05 | local fold = Instance.new( "Folder" , player) |
06 | fold.Name = "leaderstats" |
07 | local stat = Instance.new( "IntValue" , fold) |
09 | stat.Value = store:GetAsync(player.UserId) or 0 |
12 | game.Players.PlayerRemoving:Connect( function (player) |
13 | local success, err = pcall ( function () |
14 | store:SetAsync(player.UserId,player.leaderstats.Rings.Value) |