Running a function on the character when the player is leaving

I need to run a function on the Character when the player decides to leave. CharacterRemoving also launches when the character is respawning, I only need it when the player is leaving. I can’t use PlayerRemoving, because the character is destroyed before the PlayerRemoving function is ran. Any idea to run a function on the character when the player decides to leave?

--This is what I tried to do but it runs when the player respawns (Yes, ive read the API). the event was inside the PlayerAdded event
	--[[plr.CharacterRemoving:Connect(function(character)
		if character then
			SpawnBackpack(plr:FindFirstChild("Inventory"), plr, character)
			print(character)
		end
	end)]]
	
end)--PlayerAdded event end

game:GetService("Players").PlayerRemoving:Connect(function(plr)
	local profile = ProfileManagerModule.Profiles[plr]
	if not profile then return end
	profile:Release()
end)

If you’re trying to add a backpack on the player when they respawn, do not use CharacterRemoving. Instead use CharacterAdded.

No, it’s not what I am trying to do. The post says what I need.

Try this maybe?

local leavingPlayers = {}
game:GetService("Players").PlayerRemoving:Connect(function(plr)
    table.insert(leavingPlayers, plr)
    plr.CharacterRemoving:Connect(function()
        if not table.find(leavingPlayers, plr) then return end
        print("Code Goes Here")
        table.remove(leavingPlayers, table.find(leavingPlayers, plr))
    end)
end)