I was trying to make a script where the leaderstats data saves every couple minutes or seconds, but I can’t quite seem to figure out how this is done. If someone could tell me or show me how it’s done I would really appreciate it.
This is the script I have make so far. Only saves when player leaves:
local DataStoreService = game:GetService("DataStoreService")
local LeaderstatsData1 = DataStoreService:GetDataStore("LeaderstatsData1")
game.Players.PlayerAdded:Connect(function(player) -- Gets the player and connects it with the game so that you can add data into it.
local leaderstats = Instance.new("Folder", player) -- Makes a folder called leaderstats inside the player.
leaderstats.Name = "leaderstats" -- Names the folder "leaderstats" (required name otherwise won't work.)
local points = Instance.new("IntValue", leaderstats) -- Creates an int value inside the leaderstats folder.
points.Name = "Points" -- Names the int value it will show up on the 'leaderboard' (will be visible).
points.Value = 0 -- This sets the value of the 'int value' to whatever you want.
local xp = Instance.new("IntValue", leaderstats) -- Creates an int value inside the leaderstats folder.
xp.Name = "XP" -- Names the int value it will show up on the 'leaderboard' (will be visible).
local PlayerUserId = "Player_"..player.UserId
-- Load Data when player joins.
local Data1
local success, errormessage = pcall(function()
Data1 = LeaderstatsData1:GetAsync(PlayerUserId)
end)
-- Load the players data is success
if success then
if Data1 then
points.Value = Data1.Points
xp.Value = Data1.XP
end
end
end)
-- Saving data when player is leaving.
game.Players.PlayerRemoving:Connect(function(player)
local PlayerUserId = "Player_"..player.UserId
local Data1 = {
Points = player.leaderstats.Points.Value;
XP = player.leaderstats.XP.Value
}
local success, errormessage = pcall(function()
LeaderstatsData1:SetAsync(PlayerUserId, Data1)
end)
if success then
print("Player data saved!")
else
print("There was an error while saving data!")
warn(errormessage)
end
end)