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?
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)
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.
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.