Need help with the save code for the buttons

my script saves only Po1 and cannot find the rest of the buttons. I think this is related to the PlayerRemoving function and this is confirmed by a check that returns an error.

here is the code


local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local dataStore = DataStoreService:GetDataStore("PlayerVisibility")

local function saveVisible(player, buttonName, isVisible)
	local key = buttonName .. "_".. player.UserId
	dataStore:SetAsync(key, isVisible)
	print("Saved " .. buttonName)
end

local function loadVisible(player, buttonName)
	local key = buttonName .. "_" .. player.UserId
	local success, isVisible = pcall(function()
		return dataStore:GetAsync(key)
	end)
	if success then
		print("Loaded")
		return isVisible or false
	else
		return false
	end
end

function PlayerRemoving(player)
	local buttonNames = {"Po1", "Po2", "Po3"}
	local PlayerGui = player:WaitForChild("PlayerGui")
	local frame = player.PlayerGui:WaitForChild("TPmeny").Frame
	for _, buttonName in pairs(buttonNames) do
		if frame and frame:FindFirstChild(buttonName) then
			local isVisible = frame[buttonName].Visible
			saveVisible(player, buttonName, isVisible)
		else
			warn("Button not found: " .. buttonName)
		end
	end
end

Players.PlayerRemoving:Connect(PlayerRemoving)

Players.PlayerAdded:Connect(function(player)
	local buttonNames = {"Po1", "Po2", "Po3"}
	for _, buttonName in pairs(buttonNames) do
		local isVisible = loadVisible(player, buttonName)
		local frame = player.PlayerGui:WaitForChild("TPmeny").Frame
		if frame and frame[buttonName] then
			frame[buttonName].Visible = isVisible
		end
	end
end)

game:BindToClose(function(player)
	task.wait(2)	
	PlayerRemoving(player) --вызов функции для сохранения данных
end)

image

1 Like

please please PLEASE format your code with

this format
1 Like

ok. the first post did not immediately understand how to format the code

1 Like

I found the solution to the problem myself. I just made it so that the visibility is maintained immediately when I change it.

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