Need help with checkpoint system

I have a local script that creates a SpawnLocation on me when in the running state. I’m supposed to spawn at the last spawn location created but it isn’t working.

Video:

Script:

local Players = game:GetService("Players")

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

local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
local humanoid = character:WaitForChild("Humanoid")

local lastSpawnPoint = nil

-- Function to create a spawnpoint
local function createSpawnPoint()
	local spawnpoint = Instance.new("SpawnLocation")
	spawnpoint.Size = Vector3.new(4, 1, 4)
	spawnpoint.Anchored = true
	spawnpoint.Transparency = 0
	spawnpoint.CFrame = humanoidRootPart.CFrame
	spawnpoint.Parent = character

	-- Function to handle player respawning
	local function onSpawnTouched(otherPart)
		local character = otherPart.Parent
		local humanoid = character:FindFirstChildOfClass("Humanoid")

		if humanoid and humanoid.Health <= 0 then
			humanoidRootPart.CFrame = spawnpoint.CFrame
		end
	end

	spawnpoint.Touched:Connect(onSpawnTouched)
	lastSpawnPoint = spawnpoint -- Update the last spawn point
	print("Spawn point created at:", spawnpoint.Position)
end

-- Check if the player's state is running, then create a spawnpoint
if humanoid:GetState() == Enum.HumanoidStateType.Running then
	createSpawnPoint()
end

-- Listen for changes in the player's state
humanoid.StateChanged:Connect(function(oldState, newState)
	if newState == Enum.HumanoidStateType.Running then
		createSpawnPoint()
	end
end)

-- Function to respawn player at the last spawn point
local function respawnAtLastSpawnPoint()
	if lastSpawnPoint then
		humanoidRootPart.CFrame = lastSpawnPoint.CFrame
		print("Player respawned at last spawn point:", lastSpawnPoint.Position)
	end
end

-- Connect respawn function to character's death event
humanoid.Died:Connect(respawnAtLastSpawnPoint)

Set the CFrame after they respawn, not when they die.

Your script teleports the dead player’s HumanoidRootPart before they respawn with a new character. You might want to look in to using the .CharacterAdded event to update the HRP variable and teleport them after they respawn.