Fixing this code

So I have a datastore script for my game and it doesnt save
I didnt understand you NinjaFurfante, sorry

Apparently the problem is that the player’s chatacter is removed before ‘PlayerRemoving’ is fired.
I dont know how to do that

local dss = game:GetService("DataStoreService")
local mdss = dss:GetDataStore("HeadGrowthSaver")


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

	local character = player.Character or player.CharacterAdded:Wait()

	local humanoid

	while not humanoid do
		humanoid = character:FindFirstChildOfClass("Humanoid")
		if not humanoid then
			character.ChildAdded:Wait()
		end
	end
	
	local CharacterRemoving = game.ReplicatedStorage.CharacterRemoving
	
	
	local Head = humanoid.HeadScale

	local data
	local success, errormessage = pcall(function()
		data = mdss:GetAsync(player.UserId.."-Head")
	end)
	if success then
		if data then
			Head.Value = data
			print("SuccessSav")
		else
			print("No data")
		end
	else
		print("Error with saving Your Head")
		warn(errormessage)
	end
end)


game.Players.PlayerRemoving:Connect(function(player)
	
	
	
	local success, errormessage = pcall(function()
		mdss:SetAsync(player.UserId.."-Head",player.Character.Humanoid.HeadScale.Value)
	end)
	if success then
		print("Saved Head")
	else
		print("Error with saving Head")
		warn(errormessage)
	end
end)

game:BindToClose(function()
	for i, player in pairs(game.Player:GetPlayers()) do
		local success, errormessage = pcall(function()
			mdss:SetAsync(player.UserId.."-Head",player.Character.Humanoid.HeadScale.Value)
		end)
		if success then
			print("Saved Head")
		else
			print("Error with saving Head")
			warn(errormessage)
		end
	end
end)

thanks for reading

You have to declare player.Character before the player left.
I had the same issue and the only way to fix I see is to move the game.Players.PlayerRemoving:Connect(function(player) into the PlayerAdded event.

Ok, testing if I got it right

I just put the line right under the PlayerAdded line

later:
I dont think it worked

All of these posts demonstrate ways of caching characters for later use, i.e; when PlayerRemoving is fired.

You must also remove the player argument of the PlayerRemoving Event.