I'm very new to data stores and all I'm trying to do is save the value of a bool value. It does not work for some reason though, and I can't figure out why.
Here is my code:
local dss = game:GetService("DataStoreService") local playerData = dss:GetDataStore("DataStore") local function onPlayerJoin(player) local onMenu = Instance.new("BoolValue") onMenu.Name = ("onMenu") onMenu.Parent = player local userId = tostring(player.UserId) local data = playerData:GetAsync(userId) if data then onMenu.Value = data else onMenu.Value = true end end local function onPlayerExit(player) local success, err = pcall(function() local userId = tostring(player.UserId) playerData:SetAsync(userId, player.onMenu.Value) end) if not success then warn("couldn't save data") else print("success") end end game.Players.PlayerAdded:Connect(onPlayerJoin) game.Players.PlayerRemoving:Connect(onPlayerExit)
Hello, I created some comments for a DataSaving script for you to read and learn
Make sure you have API Services enabled otherwise this wont work in studio!
DataStore Script:
-- Written by MattVSNNL (Can delete the comments if you want) local PlayersService = game:GetService("Players") local dataStoreService = game:GetService("DataStoreService") local boolDataStore = dataStoreService:GetDataStore("BoolDataStore") -- Create a DataStore PlayersService.PlayerAdded:Connect(function(player) -- Check when a player joined local onMenu = Instance.new("BoolValue") -- Create a new BoolValue onMenu.Name = "onMenu" -- Call the BoolValue, OnMenu onMenu.Parent = player -- Put the BoolValue's parent to the player local onMenuData = nil -- Create a variable for the data, currently nil but when saved will be different pcall(function() -- Create a pcall just incase out script errors onMenuData = boolDataStore:GetAsync(player.UserId.."-onMenu") -- Set the onMenuData variable to what we saved! end) if onMenuData ~= nil then -- If we did save something onMenu.Value = onMenuData -- Set the value to what we saved else onMenu.Value = true -- Else put it to true end end) local bindableEvent = Instance.new("BindableEvent") -- Create a BindableEvent PlayersService.PlayerRemoving:Connect(function(player) -- Check if player is leaving pcall(function() -- Another pcall just incase the script errors boolDataStore:SetAsync(player.UserId.."-onMenu", player.onMenu.Value) -- Save the onMenu key to what the OnMenu value is end) bindableEvent:Fire() -- Fire the bindableEvent print("Saved!") -- Print saved! end) game:BindToClose(function() -- Check if the games shutting down while #PlayersService:GetPlayers() > 0 do -- Check if there is still players in the game bindableEvent.Event:Wait() -- Yield the shutdown until the players data is saved! wait() -- A wait so we don't accidentally error the script for running to much. end end)
hey you! have you ever heard of enes? if you are in trouble, better call enes!