This may take a bit of explanation because there’s a lot to unpack here.
For starters, avoid using while loops for tasks such as these. There’s a whole other thing that you can use called events, which would not only simplify your code more but also make it A LOT more optimized.
Next, if this code is not running upon respawning, it means that the script itself is getting destroyed. The executing code within scripts (loops are commonly used as such) will cease once the script has been destroyed (don’t take this as THE way to stop loops, read about them when you get the chance).
What you need to do is listen in on the humanoid.HealthChanged
signal.
humanoid.HealthChanged:Connect(function()
local isDead = humanoid.Health <= 0
if isDead then
-- code
else
-- more code
end
end)
Now instead of 30 times a second, it’ll only check for it when the player’s health changes. You can go even further and instead listen in on the humanoid.Died
event, but for simplicity’s sake we’ll stick with this.
Now you need to focus on the script being destroyed. This case makes me want to assume that the script is within the player’s gui, so check the ScreenGui’s ResetOnSpawn
property and make sure that’s false. If the script is not within the player’s gui then there’s something else that’s destroying it.
Lastly, now that your script runs even if your character respawns, you need to reconnect this event every time the player gets a new character. You can find out how to connect your code through this post, which should show you about connecting through player and character events to execute code on them properly.
EDIT: I want to clarify that the answer I gave to your issue about the code not running on future characters was because of the assumption that the script itself was getting destroyed. If that is not the case, it’s really all just because that char
parameter is always going to be the first character and not future characters. Just look through the last paragraph I’ve given, which should solve your problem there.