You can write your topic however you want, but you need to answer these questions:
What do you want to achieve? Keep it simple and clear!
I want to make it so when you die it saves your last position when you die then teleports you there
(i am thinking of making it save when you leave too after i do this)
What is the issue? Include screenshots / videos if possible!
It works the first time, but then after the first respawn it ALWAYS goes to the place of the FIRST death.
What solutions have you tried so far? Did you look for solutions on the Creator Hub?
I tried changing the code slightly, but nothing. I dont think anyone has the same problem, because its kinda specific
Here is my code (Script in ServerScriptService)
local LastPos = nil
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(char)
print("character added")
print(LastPos)
local hum:Humanoid = char:WaitForChild("Humanoid")
if LastPos ~= nil then
print(LastPos)
char:MoveTo(LastPos)
print(char:GetPivot().Position)
end
game:GetService("RunService").Heartbeat:Connect(function(time)
if hum:GetState() == Enum.HumanoidStateType.Dead then
return
else
LastPos = char:GetPivot().Position
end
end)
end)
end)
The first of your issues would definitely have been the fact that LastPos is outside of the PlayerAdded event function, meaning that it’s not unique per player. The second is that the RunService connection is completely unnecessary (Humanoid.Died works for your needs), and, since it is never disconnected after the humanoid’s death would lead to a memory leak after a while and is likely part of the reason why LastPos was always stuck on the first death (There’s likely some weird non-death state a humanoid enters after the character is destroyed).
Additionally, CharacterAppearanceLoaded is better as opposed to CharacterAdded when you need to override where a character spawns because this event more reliably fires after the engine’s built-in SpawnLocation logic happens.
A revised version of your code that does what you want looks a bit like this:
game.Players.PlayerAdded:Connect(function(plr)
local lastPos = nil
plr.CharacterAppearanceLoaded:Connect(function(char)
local hum: Humanoid = char:WaitForChild("Humanoid")
if lastPos then
char:MoveTo(lastPos)
end
hum.Died:Connect(function()
lastPos = char:GetPivot().Position
end)
end)
end)