Why is my bindtoclose not working?

local ds = game:GetService("DataStoreService"):GetDataStore("SaveData")
game.Players.PlayerAdded:Connect(function(plr)
	wait()
	local plrkey = "id_"..plr.userId
	local save1 = plr.leaderstats.dollar
	local save2 = plr.hasjoinedbefore

	local GetSaved = ds:GetAsync(plrkey)
	if GetSaved then
		save1.Value = GetSaved[1]
		save2.Value = GetSaved[2]
	else
		local NumberForSaving = {save1.Value, save2.Value}
		ds:GetAsync(plrkey, NumberForSaving)
	end
end)

		game:BindToClose(function()
	game.Players.PlayerRemoving:Connect(function(plr)
		ds:SetAsync("id_"..plr.userId, {plr.leaderstats.dollar.Value, plr.hasjoinedbefore.Value})	
	end)
end)

and the end where it has bindtoclose isn’t working im probably doing this wrong so i need help please a thank

game:BindToClose only fires when the Server closes, tryna put game.Players.PlayerRemoving outside of it

when i put game.Players.PlayerRemoving outside of it a error pops up saying

BindToClose failed because the model is already being closed.

wait tryna remove the game:BindToClose, and just the game.Players.PlayerRemoving so like

game.Players.PlayerAdded:Connect(function()
end

game.Players.PlayerRemoving:Connect(function()

end

yeah but my originial problem was that the data save wasn’t saving cause studio was closing too fast

and this is how i use game:BindToClose() and game.Players.PlayerRemoving in my data handler

game.Players.PlayerRemoving:Connect(function(player)
	SaveData(player) -- a function i made
end)

game:BindToClose(function()
	for i, player in pairs(game:GetService("Players"):GetChildren()) do
		if player then
			player:Kick("This Particular Server is Shutting Down, Please Rejoin.")
		end
	end

	task.wait(5)
end)

OHHHH YOU NEED TO ADD WAIT(), ahem “task.wait(5)” or change the 5 to how long you want the server take to close

do i just copy and paste that or something

copy this:

game:BindToClose(function()
	task.wait(5) -- change the "5" to how long you want your server takes to close
end)

it should work now

do i keep the player.removing???

yep of course, you need to detect if the player leaves as well to save that player’s data

it didn’t work !!!

game:BindToClose(function()
game.Players.PlayerRemoving:Connect(function(plr)
		task.wait(30)
		ds:SetAsync("id_"..plr.userId, {plr.leaderstats.dollar.Value, plr.hasjoinedbefore.Value})	
	end)
end)

NOOO- dont put the game.Players.PlayerRemoving inside the BindToClose

do it like this:

remove the task.wait inside the game.Players.PlayerRemoving

or just copy this:

it should work.

game.Players.PlayerRemoving:Connect(function(plr)
		ds:SetAsync("id_"..plr.userId, {plr.leaderstats.dollar.Value, plr.hasjoinedbefore.Value})	
	end)
end)

game:BindToClose(function()
	task.wait(5) -- change the "5" to how long you want your server takes to close
end)

ok ima see if it works!!!

it works lets gooooo!!!

1 Like

finallyyyy ahahaha, youll encounter more problems someday lol. goodluck with it!