I made a datastore script and in my game I also made scripts that changes the value of the “DarkMode” in the folder “SaveSettings” but when I change the setting, it changes for the player but when I rejoin it isn’t saved, how do I fix this
local DataStore = game:GetService("DataStoreService")
local myDataStore = DataStore:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(plr)
local SaveSettings = Instance.new("Folder")
SaveSettings.Name = "SaveSettings"
SaveSettings.Parent = plr
local DarkMode = Instance.new("BoolValue")
DarkMode.Name = "DarkMode"
DarkMode.Parent = SaveSettings
DarkMode.Value = false
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(plr.UserId.."-DarkMode")
end)
if success then
DarkMode.Value = data
else
print("There was an error while giving Player Data.")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local success, errormessage = pcall(function()
myDataStore:SetAsync(plr.UserId.."-DarkMode", plr.SaveSettings.DarkMode.Value)
end)
if success then
print("Player Data successfully saved!")
else
print("There was an error while saving Player Data.")
warn(errormessage)
end
end)
Are you sure DarkMode’s value is changing on the server? You might only be changing it in a local script, not letting the server script see the change, making it default to false.
What moon meant is that the settings may not be replicated back to the server from the client. If PlayerA changes the value of darkmode in a local script (say, from clicking a button), the server would not see the update. The local script would have to fire a RemoteEvent back to the server in order to change it. For example:
---Local Script
DarkModeButton.MouseButton1Click:Connect(function()
game.ReplicatedStorage.DarkModeEvent:FireServer()
end)
---Server Script
game.ReplicatedStorage.DarkModeEvent.OnServerEvent:Connect(function(player)
local plr = game.Players:FindFirstChild(player.Name)
plr:FindFirstChild("SaveSettings").DarkMode.Value = not plr:FindFirstChild("SaveSettings").DarkMode.Value
end)
I believe this should work, but basically you want the client to tell the server that they updated their DarkMode settings. In order to do that you would fire a RemoteEvent. On the server you want to connect a function to that event. The first argument passed to the function (on the server) is the player object.
I mean just for testing you can make the autosave in the playeradded event and copy your saving script from playerremoving into a while wait(20) do loop. While wait() loops aren’t the best to always do but at least for eating it should be fine.