I spent the last few hours rewritting a horrible DataStore script as i feel its best to get this as perfect as possible since it saves valuable information.
Keep in mind im a completely new scripter so feedback is what im aiming for and how I could improve this in anyway possible.
At first i attempted to do this in DataStore2 and completely got lost so after researching using tables with DataStore i ended up with this.
local Players = game:GetService("Players") local DataStoreService = game:GetService("DataStoreService") local TestDataStore = DataStoreService:GetDataStore("bloxbrawl") local data = { ["Levels"] = 1, ["Exp"] = 0, ["ExpNeed"] = 200, ["Gold"] = 100 } Players.PlayerAdded:Connect(function(Player) local DataFromStore = nil local stats = Instance.new("Folder") stats.Name = "Data" stats.Parent = Player for name, value in pairs(data) do local new = Instance.new("IntValue") new.Name = name new.Value = value new.Parent = stats end local s, e = pcall(function() DataFromStore = TestDataStore:GetAsync("uid-" .. Player.UserId) end) if s then print("Getting Data For: " .. Player.Name) if DataFromStore then for name, value in pairs(DataFromStore) do Player.Data[name].Value = value end print("Data Loaded For: " .. Player.Name) else print("Created New Data For: " .. Player.Name) end else warn("Error Getting Data For: " .. Player.Name) end end) game.Players.PlayerAdded:Connect(function(plr) wait(.1) local Exp = plr.Data.Exp local Levels = plr.Data.Levels local ExpNeed = plr.Data.ExpNeed while wait() do if Exp.Value >= (100 * (Levels.Value + 1)) and Levels.Value <= 399 then Levels.Value = Levels.Value + 1 Exp.Value = Exp.Value - ExpNeed.Value ExpNeed.Value = ExpNeed.Value + 100 game.ReplicatedStorage.LevelSystem.LevelUpGui:FireClient(plr) end end end) Players.PlayerRemoving:Connect(function(Player) local DataForStore = {} for name, value in pairs(Player.Data:GetChildren()) do DataForStore[value.Name] = value.Value end local success = pcall(TestDataStore.SetAsync, TestDataStore, "uid-" .. Player.UserId, DataForStore) if success then print("Successfully Saved Data For: " .. Player.Name) end end)
Should a BindToClose be added? Sorry if that seems like a stupid question.
Thank you ahead for the constructive criticism!
I see nothing wrong with your script apart from saying you should the 2nd Variable of pcall at line 71. And also mentioned, you should add a BindToClose. The problem with Players.PlayerRemoving
is that it doesn't count for the last player in the server, Roblox recommends that you use game:BindToClose()
for saving data just in case for that last player. game:BindToClose()
allows functions to run for 30 seconds before the server shuts down.
Here's more information about game:BindToClose() (also this link shows you how to save data)