Datastore script not running for some reason?

game.Players.PlayerRemoving:Connect(function(plr)
   print("F")
   MoneyStore:SetAsync(plr.UserId,plr.leaderstats.Money.Value)
   print("E")
   KillsStore:SetAsync(plr.UserId,plr.leaderstats.Kills.Value)
   print("A")
   GunsStore:SetAsync(plr.UserId,httpService:JSONDecode(plr.Guns.Value))
   print("?")
end)

Prints F, but nothing else? i have no idea why? if u want entire script ask me. Thank you!

1 Like

The reason is because when the last player leaves (which is probably what happens in a single-player test), all server scripts terminate. Try using game:BindToClose() which gives you 30 seconds to run your code. I would recommend doing something like:

local Players = game:GetService("Players")
game:BindToClose(function()
     for _, player in Players:GetPlayers() do --Loop through each player still in the game
          task.spawn(function() --Creates a new thread, so multiple players can save at once
               --Save data here; use player variable
          end)
          task.wait(0.1) --Avoid overloading requests
     end
     task.wait(0.25) --Buffer time, maybe unnecessary but just in case. Don't set too high for reasons below.
end)

I also highly recommend implementing protected calls to deal with any dropped data store requests. (They can throw errors – which can stop all the other player’s data from saving)

On top of this, I would recommend still having the Players.PlayerRemoving event. To ensure you don’t double-save when the server ends, you can use something like a loadedPlayers table. When the player joins and their data is loaded, add them to the table. When either game:BindToClose or Players.PlayerRemoving fires, don’t save their data if they aren’t in the table. If they are in the table, remove them from the table and save it.

(If I remember correctly) Roblox studio won’t finish the playtest until :BindToClose() is finished, so doing something like task.wait(30) will make studio lag for 30 seconds when you click stop

Sorry if this was overcomplicated, ask me if you have any questions.

I put the script in serverscriptservice doe? why would that happen?

1 Like

It’s because Roblox can’t let your game run forever when nobody is playing it anymore. They need to be efficient with server resources. There are a lot of code examples (say a while true loop that moves a part 1 stud every second) that don’t need to run when nobody is playing the game (that example would never stop running all by itself). So, they allow you to run extra code for 30 seconds after, and make you define it specifically with game:BindToClose() so they know you actually need it to run.

To test it i made a server with two people and left on one client. You were correct! thank you for the help!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.