Disconnecting an Event from inside the Event

I’m trying to make a system where a player is detected to have died, but I want it to only run once.
My current code follows this:

player.CharacterAdded:Connect(function(char)
   ev = char.Humanoid.HealthChanged:Connect(function(health)
      if health <= 0 then
         --Code
         ev:Disconnect()
      end
   end)
end)

Is this the best way to do it? Can I move the “:Disconnect()” Statement to the beginning of the event, before “–Code,” so that it can block any event calls that happen before the first call is complete?

2 Likes

Why don’t you do this?

player.CharacterAdded:Connect(function(char)
local hi = char.Humanoid.Died:Connect(function()
--code
hi:Disconnect()
end)
end)

yeah that’s fine, if I’m understanding what you’re saying correctly

local test

test = workspace.ChildAdded:Connect(function(child)
	test:Disconnect()
	print(child.Name)	
end)

:Disconnect() stops the event from firing again, the rest of the code will still run after calling :Disconnect()

also humanoid has a Died event which is only called once, so you can use that instead

player.CharacterAdded:Connect(function(char)
  	char.Humanoid.Died:Connect(function()
	-- code
   end)
end)
8 Likes

The easiest way to do this is create a local variable right before you set a connection. That will make it so the thread inside the connect event can access the variable

player.CharacterAdded:Connect(function(char)
local connection
connection = char.Humanoid.HealthChanged:Connect(function(health)
if health <= 0 then
connection:Disconnect()
end
end)
end)

4 Likes

Where do you declare ev? Typically even the way you’re assigning the connection should be illegal.

You are able to move the disconnect method to the top of the event and I would encourage you do so as well so that your other code does not delay when the event disconnects. Disconnect will detach the RBXScriptConnection from the RBXScriptSignal’s list of connections to fire and that’s it. The rest of your code will continue to run as expected.

I wonder though, is there a specific reason why you aren’t using the dedicated event for this, Died? What you hope to accomplish is a little vague.

1 Like

I wanted to do:

local ev = --etc

But It raised a warning saying it couldn’t be accessed from within the event function, so I just eliminated the local and it seemed to fix itself. Of course, a more proper way would be to declare the variable before.

I didn’t know that .Died was thing, I did a lackluster search in the Humanoid API. Though I could’ve saved myself some time, this helps for when I need events to disconnect from within them.