CharacterRemoving not running

I’m attempting to create a script which saves the player character’s position upon leaving. Unfortunately it doesn’t seem to be running upon the player leaving. I’m getting no errors.

game.Players.PlayerRemoving:Connect(function(player)
	local dataStorage = game:GetService("DataStoreService"):GetDataStore("KeyStore")
	local plrFolder = plrData:FindFirstChild(player.Name)
	
	print("left")
	player.CharacterRemoving:Connect(function(character)
		print("destroy2")	
		local saving =
		{
			["PosX"] = character:FindFirstChild("HumanoidRootPart").Position.X,
			["PosY"] = character:FindFirstChild("HumanoidRootPart").Position.Y,
			["PosZ"] = character:FindFirstChild("HumanoidRootPart").Position.Z,
			["PlayerSpawn"] = player.RespawnLocation.Name,
			["Skills"] = {}
		}
		
		for i, v in pairs(plrFolder:FindFirstChild("Skills"):GetChildren()) do
			table.insert(saving["Skills"], v.Name)
		end
		
		print("destroy1")
		data:SetAsync(player.UserId, saving)
		wait(5)
		print("destroy")
		plrFolder:Destroy()
	end)
end)

It only manages to print “left” and never gets to the other 3 prints, any help would be appreciated.

Why are you using CharacterRemoving? Wouldn’t it make more sense to just reference the player’s character as soon as PlayerRemoving runs?

Already tried that, it simply appears as nil as the character doesn’t exist at that moment.

That makes me believe that the Character gets removed before the player does. Perhaps you could detect when a player’s Character is removed first, save all the important data in a variable, and then once PlayerRemoved is called utilize the data to save whatever you need to save.

I attempted to create a separate CharacterRemoving event within a PlayersAdded function and even then it didn’t run. It seems that the event itself is problematic for some odd reason.

To clarify, do you mean to just save the values through a while loop or whenever they update as said variable and then use that variable rather than rely on the character itself?

I attempted that as well, but CharacterRemoving doesn’t run at all. The prints don’t fir event when it is in a PlayersAdded function.

@liuthemoo already suggested that, unfortunately the character comes up as nil when only using PlayerRemoving, so that doesn’t work either.

Well i dont think so this thread will help you but check it out Here