Attempting to remove an object when a player has died

I want this script to remove the ui object it it parented to when the local player’s character dies. The script i have works half the time, and errors that Player.Character is nil otherwise.

wait()

local char = game.Players.LocalPlayer.Character

char:FindFirstChildOfClass("Humanoid").Died:Connect(function() script.Parent:Destroy() end)

I have attempted to replace game.Players.LocalPlayer.Character with game.Players.LocalPlayer.CharacterAdded:Wait() and game.Players.LocalPlayer.Character or game.Players.LocalPlayer.CharacterAdded:Wait() but all these seem to do is put it in an infinite waiting loop and never actually remove the ui object.

3 Likes

Do you have this in a Script or a LocalScript?

2 Likes

This code is written inside a LocalScript

1 Like
game:GetService("Players").PlayerAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function()
local Humanoid = Player.Character:WaitForChild("Humanoid")
Humanoid.Died:Connect(function()
local GUI = Player:FindFirstChild("PlayerGui"):FindFirstChild("Put the name of your gui here")
if GUI then
GUI:Destroy()
end
end)
end)
end)
2 Likes

From the wiki’s Player.Character documentation :

LocalScripts that are cloned from StarterGui or StarterPack into a player’s Backpack or PlayerGui are often run before the old Character model is deleted. Player.Character still refers to a model, but that model’s parent is nil and it is has been destroyed. Because of this, if the Character already exists, you should check to make sure that the Character’s parent is not nil before using it.
So if you’re writing a LocalScript , do this:

local player = game.Players.LocalPlayer
local character = player.Character
if not character or not character.Parent then
character = player.CharacterAdded:wait()
end
2 Likes

This has functioned properly, Thank you

1 Like