How do I use DataStore? I want to make a game that I can save my leaderstats, But I dont know how to.
I need to know so I can make a cool game.
How do I use DataStore? I want to make a game that I can save my leaderstats, But I dont know how to.
I need to know so I can make a cool game.
Hello, you can learn here:
Click on every word that is marked with a different color from the other texts, so that you can see how to use them. Example: UserId, GetAsync, SetAsync and others.
To create a DataStore you would do
local myDataStore = game:GetService("DataStoreService"):GetDataStore("datastore-name")
After that you would use a pcall to save the data when the player joins and leaves.
I suggest reading this article:
I don’t know what you mean by your definition of pcall, because it actually detects and handles errors in a function and returns true if there aren’t any.
Yes, when saving data its best to use pcall if the data couldn’t be saved it would return false and if it is successful it returns true
Firstly you have to enable API Services in Game Settings > Security > API Settings variables
local DataStoreService = game:GetService("DataStoreService") -- Defines the service
local DataStore = DataStoreService:GetDataStore("Put the name of your datastore here") -- Creates an acess to your own DataStore
game.Players.PlayerAdded:Connect(function()
-- Create leaderstats here
-- Now we will load the leaderstats for the current player who just joined
local PlayerUserId = "Player_"..player.UserId -- Creates the same key as earlier to access the players datastore
local data
local success, errormessage = pcall(function() -- Wraps in pcall to catch any errors
data = DataStore:GetAsync(PlayerUserId) -- Accesses and loads the players data
end)
if success and data then -- If it was loaded successfully
-- if you used a table do this;
Kills.Value = data[1]
Deaths.Value = data[2]
-- if you saved one value do this;
Kills.Value = data
elseif data == nil then -- If theres no data (players first time playing)
Kills.Value = 0 -- Sets the value to the default if its their first time playing
Deaths. Value = 0
elseif errormessage then
warn(errormessage) -- If theres an error it will warnthe error in the output tab but will not error the script
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local PlayerUserId = "Player_"..player.UserId -- This is a key that can only be accessed by the player
local data = player.leaderstats -- You can either save this as a value or table
DataStore:SetAsync(PlayerUserId, data) -- This saves the data when the player leaves
end)