local DataStore = game:GetService("DataStoreService") local killsds = DataStore:GetDataStore("Kills") game.Players.PlayerAdded:connect(function(player) local stats = Instance.new("Folder",player) stats.Name = "Stats" -- creates a leaderboard -- CREATES KILLS VALUE -- local killsvalue = Instance.new("NumberValue", stats) killsvalue.Name = "Kills" -- creates a leaderstat value killsvalue.Value = killsds:GetAsync(player.UserId) or 0 -- gets past value killsds:SetAsync(player.UserId,killsvalue.Value) -- sets a new value -- LEAVE BACKUP SAVE -- game.Players.PlayerRemoving:connect(function(player) print("Saving Data for user "..player.UserId) killsds:SetAsync(player.UserId,player.Stats.Kills.Value) print(player.UserId.."'s Data has been saved successfully.") if error then print("DATA ERROR: "..player.UserId.."'s Data has been saved unsuccessfully") end end) end)
I know you have to do something with a RemoteFunction but I'm not exactly sure what to do. Help is much appreciated.
You connected the events a little wrong. To put it simply, this is how your code is:
local DataStore = game:GetService("DataStoreService") local killsds = DataStore:GetDataStore("Kills") game.Players.PlayerAdded:connect(function(player) --Execute game.Players.PlayerRemoving:connect(function(player) --execute end) end)
To put it simply, you can't connect it this way. It should be:
local DataStore = game:GetService("DataStoreService") local killsds = DataStore:GetDataStore("Kills") game.Players.PlayerAdded:connect(function(player) --Execute end) game.Players.PlayerRemoving:connect(function(player) --execute end)
Now, there are a few things to note: First, the player removing event will Not fire in time if the last person is leaving the server, or if the server is shutdown for whatever reason, as the game is closing. Secondly, you have some un required code. If the only thing you want to save is kills, then the final script should look like:
local DataStore = game:GetService("DataStoreService") local killsds = DataStore:GetDataStore("Kills") game.Players.PlayerAdded:Connect(function(player) -- connect must be Connect btw local stats = Instance.new("Folder",player) stats.Name = "Stats" -- creates a leaderboard local killsvalue = Instance.new("NumberValue", stats) killsvalue.Name = "Kills" -- creates a leaderstat value killsvalue.Value = killsds:GetAsync(player.UserId) or 0 -- gets past end) game.Players.PlayerRemoving:Connect(function(player) killsds:SetAsync(player.UserId,player.Stats.Kills.Value) end) game:BindToClose(function() -- if the last player in the game leaves, don't close the server down until it's saved local p = game.Players:GetPlayers() for a=1,#p do local player = p[a] killsds:SetAsync(player.UserId,player.Stats.Kills.Value) end end)