I have a checkpoint system. You spawn in at the first checkpoint with the value Enabled set to true. However when you step on another checkpoint that checkpoint is set to true and the last checkpoint is set to false. The problem is when the player dies the value for the first checkpoint resets back to true and now we have two true values for enabled. Now when the player dies and respawns they respawn at the first checkpoint instead of the second.
-- Define the starting and ending color and material
local startColor = Color3.new(1, 0.666667, 1)
local endColor = Color3.new(0, 1, 0)
local startMaterial = Enum.Material.SmoothPlastic
local endMaterial = Enum.Material.Neon.Value
local CollectionService = game:GetService("CollectionService")
local CheckPoints = CollectionService:GetTagged("CheckPoints")
-- Define the duration of the color change in seconds
local duration = 1
-- Keep track of the last checkpoint the player touched
local lastCheckpointValue = Instance.new("ObjectValue")
lastCheckpointValue.Name = "LastCheckpoint"
lastCheckpointValue.Value = nil
lastCheckpointValue.Parent = game.Players.LocalPlayer
-- Define the function to tween the part's color and material
local function tweenColor(part)
-- Create the color and material tweens
local colorTween = game:GetService("TweenService"):Create(part, TweenInfo.new(duration), {Color = endColor})
local materialTween = game:GetService("TweenService"):Create(part, TweenInfo.new(duration), {Material = endMaterial})
-- Play the tweens in parallel
colorTween:Play()
materialTween:Play()
end
-- Set up the Touched event for each checkpoint
for i, checkpoint in ipairs(CheckPoints) do
checkpoint.Touched:Connect(function(hit)
if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
-- Disable the last checkpoint the player touched
local lastCheckpoint = lastCheckpointValue.Value
if lastCheckpoint then
lastCheckpoint.Enabled = false
end
-- Set the new checkpoint as the last checkpoint the player touched
lastCheckpointValue.Value = checkpoint
-- Enable the new checkpoint
checkpoint.Enabled = true
-- Tween the checkpoint's color and material
tweenColor(checkpoint)
end
end)
end
-- Set the player's respawn location based on the last checkpoint they touched
game.Players.LocalPlayer.CharacterAdded:Connect(function(character)
character.Humanoid.Died:connect(function()
if character.Humanoid.Health == 0 then
local lastCheckpoint = lastCheckpointValue.Value
if lastCheckpoint and character:FindFirstChild("Humanoid") then
local spawnLocation = lastCheckpoint.SpawnLocation
character.HumanoidRootPart.CFrame = spawnLocation.CFrame
end
end
end)
end)