Hello, so I pretty much had a simple question about datastores.
Currently this is the main script →
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
local function onPlayerJoin(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Time = Instance.new("IntValue")
Time.Name = "Time"
Time.Parent = leaderstats
local playerUserId = "Player" .. player.UserId
local data = playerData:GetAsync(playerUserId)
if data then
Time.Value = data
else
Time.Value = 0
end
end
local function onPlayerExit(player)
local success, err = pcall(function()
local playerUserId = "Player" .. player.UserId
playerData:SetAsync(playerUserId, player.leaderstats.Time.Value)
end)
if not success then
warn('Could not save data!')
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
local function onPlayerJoin(player)
while true do
wait(60)
player.leaderstats.Time.Value = player.leaderstats.Time.Value + 1
end
end
Very old and outdated. So I was trying to replace the script, with this →
--[ SERVICES ]--
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("PlayerData")
local service = game:GetService("MarketplaceService")
--[ FUNCTIONS ]--
game.Players.PlayerAdded:Connect(function(Player)
--[{ LEADERSTATS }]--
local Leaderstats = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
Leaderstats.Parent = Player
local Time = Instance.new("IntValue")
Time.Name = "Time" -- changing name here (points, levels, time, etc.)
Time.Value = 0 -- default value
Time.Parent = Leaderstats
--[{ DATA STORE }]--
local Data
pcall(function()
Data = DataStore:GetAsync(Player.UserId) -- Get Data
end)
if type(Data) ~= "table" then
Data = nil
end
if Data then
Time.Value = Data.Time
end
--[{ TIME GIVERS }]--
local incrementValue = 1 -- value when adding points
coroutine.resume(coroutine.create(function() -- gives 1 point every minute
while true do
wait(60) -- every minute
Time.Value = Time.Value + incrementValue -- adds points based off of the incrementValue
end
end))
end)
game.Players.PlayerRemoving:Connect(function(Player) -- save function here
--[{ DATA STORE SAVING }]--
DataStore:SetAsync(Player.UserId, { -- gets data
Time = Player.leaderstats.Time.Value
})
end)
Cleaner and more efficient, although I ran into the problem of the datastores resetting.
As in let’s say a player had 1000 Time when I installed this new script, it reset the player’s data back to 0 Times! Which I want to avoid? How could this be possible?
This is the same game and everything. I thought : local DataStore = DataStoreService:GetDataStore("PlayerData")
Would be grabbing that datastore? What am I doing wrong?