Hey, so I have a local script that detects when any of the values inside the player change, then add the new values to a dictionary within the local script, and when it’s time to save it will fire a remote function to save it. But after reading some posts it looks like that’s not the best option for when a player is leaving. How else could I save the table to the datastore when the player leaves?
Why are you having the client requesting the save? I would recommend just listening for PlayerRemoving
on the server, as well as incorporating both autosaving at an interval and on closing with game:BindToClose()
.
rewrite your thing to be server based because having the data on the server means that you can save easier and actually hold the data just in case the save doesnt work
I originally used a local script because I didn’t know how to make different dictionaries for each player in a server script, I only know how to add things to the dictionary. Is there a way to make a new dictionary automatically when a player joins that’s named their username?
Yeah, though I would recommend learning and understanding more on how all of these things work as it’s not really a beginner topic. Here’s an example:
local Players = game:GetService("Players")
-- we use this table to store players' data
local StoredData = {}
local function onPlayerAdded(player)
-- load and/or create data
StoredData[player] = theirData
end
local function onPlayerRemoving(player)
if StoredData[player] ~= nil then
-- save data
StoredData[player] = nil
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoving)
-- manually fire in case this script runs late and
-- players are already in game
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAdded, player)
end
-- save on game close
game:BindToClose(function()
-- your saving method. basic example:
for player, playerData in StoredData do
-- save data
end
end)
-- save at an interval
task.spawn(function()
while true do
-- save data every 5 minutes
task.wait(300)
end
end
@MADELlNEE
use a module script, clone it for every player joins and name it with their user id or something you like.
store it in server storage
use server script inside server script service
.OnPlayerRemoving(function()
local module=require(module)
datastore:SetAsync(key,module[data])
end)
--once saved data to datastore, just destroy that player's modulescript