Here is the script:
-- Define variables local DataStoreService = game:GetService("DataStoreService") local Players = game:GetService("Players") -- You should put your data store as a separate variable then the service one local DataStore = DataStoreService:GetDataStore("NameHere") -- Loads the data back to the player game.Players.PlayerAdded:Connect(function(player) -- Creates the stats local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player local points = Instance.new("IntValue") points.Name = "Points" points.Parent = leaderstats local coins = Instance.new("IntValue") coins.Name = "Coins" coins.Parent = leaderstats local Key = "player-"..player.UserId -- key pcall(function() -- Stops errors -- Data Stores can error so thats why I did this SavedStats = DataStore:GetAsync(Key) end) -- Gives the player the data if they have data else create a datastore for them if SavedStats then points.Value = SavedStats[1] coins.Value = SavedStats[2] else local Values = { points.Value; coins.Value } pcall(function() -- Stops errors DataStore:SetAsync(Key, Values) end) end Key = "player-"..player.UserId valuesToSave = { player.leaderstats.Points.Value; player.leaderstats.Coins.Value} pcall(function() -- Stops errors DataStore:SetAsync(Key, valuesToSave) end) game.Players.PlayerRemoving:Connect(function(player) pcall(function() DataStore:SetAsync(Key, valuesToSave) end) end) end)
Thanks for the help!
When you use pcall
, it returns two values. The first value is a boolean
value. This is either true if the function ran without error, or false if the function had an error. The second value is whatever you return
to the function, whatever the function's value is, or if it errors then it is the error message. However, we don't have to bother with the second value.
Knowing this, whenever you use pcall
on a function you should set it equal to two variables.
local success, value = pcall(function() end)
Also, you have to check if the function ran without errors. Since, as I said above, the first value passed through is a boolean
value, we can check if the first variable is true or false. I named ours success
because it makes sense that way.
local success, value = pcall(function() --run stuff-- end) if success == true then --run more stuff-- else --ERROR-- end
So let's try using pcall
in an example.
local success, value = pcall(function() DataStore:SetAsync(Key, Values) end) if success == true then points.Value = SavedStats[1] coins.Value = SavedStats[2] else --Error-- end
As you can see here, we're trying to set values to the data store, and if it doesn't error and success == true then we can assign the values.
However, you don't need to use pcalls
here, I recommend watching PeasFactory's video on Data Stores. https://www.youtube.com/watch?v=VXcbZ2kurvk