LocalScript in Tool breaks when player respawns

Hi! I’ve been working on my own input based tool script for the past few days,
and I ran into an issue where the script will call an infinite yield on “WaitForChild()”,
but only does this when the player respawns.

This makes the tool only functionable if the player hasn’t died yet,
and I’m not quite sure what I need to do in order to prevent this error from popping up.

Error

image

Code

image

Does anyone know the cause of this?
Thanks in advance.

5 Likes

For some reason, the moment the LocalScript runs, the Player.Character property is a reference to the player’s old character which has been destroyed and therefore has parent nil.
Not entirely sure why this is the case, I ran into this problem and was baffled by it for a while before finding the problem and a workaround. This may be a bug, but for now you can change your while condition to:

while not char or not char.Parent do

Seemed to work fine for me, just tested it again to confirm.

13 Likes

That’s very weird. I even tried destroying the tool itself when the humanoid dies,
and one would expect it’s references to reset, but it didn’t.

Anyways, thanks! It seems to be working fine now.

If you’re using a LocalScript for a tool, or in PlayerGui (without the parent being a gui, or if that’s the case, its “ResetOnSpawn” property is set to false), and you store the player’s character and its content (Humanoid, HumanoidRootPart, etc.) in variables, I suggest you update the variables when the player respawns to avoid the script breaking.

Just use this method:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

Player.CharacterAdded:Connect(function(Char)
	Character = Char
	Humanoid = Char:WaitForChild("Humanoid")
	HumanoidRootPart = Char:WaitForChild("HumanoidRootPart")
end)

(I wrote this down without testing, but hopefully it works for you.)

5 Likes