Problem with a local script

Heyy! I have a problem with my local script…
The output : Players.gentilmatheo.PlayerGui.CameraScript.LocalScript:4: attempt to index nil with ‘Destroy’

while wait() do
	if game.Players.LocalPlayer.Character.Humanoid.Health <= 0 then
	script.Parent:Destroy()
	end
end

I dont think you need the = sign.

If the script is deleted, then don’t worry. I believe the loop will keep running despite being deleted, so script.Parent will no longer exist and script.Parent:Destroy() will thus error.

You can’t just assume the character will exist immediately, either use WaitForChild or CharacterAppearanceLoaded

local players = game:GetService("Players")

local function onPlayerAdded(player)
    player.CharacterAppearanceLoaded:Connect(function(character) 
        local humanoid = character.Humanoid
        humanoid.Died:Connect(function()
            script.Parent:Destroy()
        end)
    end)
end


players.PlayerAdded:Connect(onPlayerAdded)
-- formatted and written right here

Although destroying a script doesn’t necessarily remove the thread from memory.

If you want the script to be removed when the character dies just place it in StarterCharacterScripts, this loop is unnecessary.

1 Like

Ok so theres an event for when your humanoid dies, you can use that to destroy the script.

Local Con = nil -- Var for disconnection
Con = Humanoid.Died:Connect(function()
   Con:Disconnect() -- Disconnect it just incase (won't probably cause a memory leak)
   script.Parent:Destroy()
end)

The disconnection isn’t needed but I do it as a habit just incase, because when the script is destroyed the connection is automatically disconnected iirc.