A question about "Character ChildAdded": Any differences?

So I have a local script inside a Gui (that I strictly cannot allow to reset after death) and whenever the player takes a seat or holds an item, the BoolValues will be set to true. However, it wasn’t working after death even if I referred the new character to the variable. I did fix it though, just wondering what’s the difference and why doesn’t the other one work…

I have encountered this issue so many times so I had to set it to reset some Guis after death that I worked on before. On this one, I really had no other choice, I can’t reset this Gui after death and I had to figure it out.

Working:

player.CharacterAdded:Connect(function(character)
	char = character -- Replaces the local "char" variable with the new character
	humanoid = char:WaitForChild("Humanoid")
	
	holdingItem.Value = false
	sitting.Value = false
	
	char.ChildAdded:Connect(function(tool)
		if tool:IsA("Tool") then
			holdingItem.Value = true
		end
	end)
	char.ChildRemoved:Connect(function(tool)
		if tool:IsA("Tool") then
			holdingItem.Value = false
		end
	end)
	humanoid.Seated:Connect(function()
		if humanoid.Sit == true then
			sitting.Value = true
		else
			sitting.Value = false
		end
	end)
end)

Not working:

player.CharacterAdded:Connect(function(character)
	char = character -- Replaces the local "char" variable with the new character
	humanoid = char:WaitForChild("Humanoid")
	
	holdingItem.Value = false
	sitting.Value = false
end)

char.ChildAdded:Connect(function(tool)
	if tool:IsA("Tool") then
		holdingItem.Value = true
	end
end)
char.ChildRemoved:Connect(function(tool)
	if tool:IsA("Tool") then
		holdingItem.Value = false
	end
end)
humanoid.Seated:Connect(function()
	if humanoid.Sit == true then
		sitting.Value = true
	else
		sitting.Value = false
	end
end)

The code you had that didn’t work didn’t work because when a character is reset, it Destroy()s the character model, which in turn destroys all events to it, even the events you set up. Because the gui is not set to reset on spawn, the events are only made once, so when they are destroyed by a reset, they are not made again.

In your working example, you put the events in the characteradded event, it works because it recreates the events on the new character. So when the event is fired when a character is added again, it also sets up the events again, the only time this will stop working is if the player leaves, which by that point will not matter

Basically, working code works because it recreates the events on the new character, non-working code does not work because the events are only made once and are disconnected once a reset happens

2 Likes

So that’s why the bottom part (ChildAdded) doesn’t work when I tried to replace the character variable…

Makes sense now and the fact that I didn’t even know that any event connected to an object also gets destroyed if the object gets destroyed. This helps so much, thank you so much! :smiley:

1 Like