Trying to have a script stop a connection for a bit when a player dies and come back after the player respawns and tried this
local function LoopCheck()
local Character = Player.Character or Player.CharacterAdded:Wait()
Connection1 = Character.ChildAdded:Connect(EquippedItem)
local Coro = coroutine.create(function()
while task.wait() do
if not Character or Character.Humanoid.Health == 0 then
Connection1:Disconnect()
Character = Player.Character or Player.CharacterAdded:Wait()
Connection1 = Character.ChildAdded:Connect(EquippedItem)
end
end
end)
end
But this doesnt work and i dont really got any other ideas currently on how i could do this
The Character variable won’t just magically disappear, you have to do if not Player.Character or Player.Character.Humanoid.Health == 0 and then you need to wait for the character to despawn before just assigning the character variable again.
Is this a server script? This will cause a memory leak if so.
local Coro = coroutine.create(function()
while task.wait() do
if not Character or Character.Humanoid.Health == 0 then
Connection1:Disconnect()
Character = Player.Character or Player.CharacterAdded:Wait()
Connection1 = Character.ChildAdded:Connect(EquippedItem)
end
end
end)
Not exactly. It disconnects the connection1 and then reconnects it after waiting for the character to be added. Therefore, no memory leaks should be present.
Memory leaks aren’t limited to event connections, that while loop is never broken out of (which could cause alternate threads to persist in memory forever).
while task.wait() do
if not Character or Character.Humanoid.Health == 0 then
Connection1:Disconnect()
Character = Player.Character or Player.CharacterAdded:Wait()
Connection1 = Character.ChildAdded:Connect(EquippedItem)
else
break --Break loop in order for the coroutine to be closed (as it reaches the end of its execution).
end
end
If this is a local script inside the StarterCharacterScripts container then this isn’t necessary (as the script is destroyed when the character is removed anyway) otherwise this is necessary.
Lacking information regarding the script’s contents and location, potentially, indefinite loops should still have a breaking condition though, if not player.Parent then may be a more fitting breaking condition.
its in starterplayer, wouldn’t just disappear after the player disconnects? plus i didnt see a need for a break if i needed it to run for the entire time