I’ve got a set of training dummies that I’ve rigged to respawn automatically when they’ve been killed. For testing purposes (I’m trying to figure out the proper behavior to address memory leaks) they have no scripts inside them whatsoever, and they respawn with the help of a single script. As far as I know, no other reference to the dummies exist in memory.
And yet, when the dummies are killed and replaced, the Instances section of the Server memory log goes irreversibly upwards, and never returns back down.
I’ve read countless articles on proper coding practice for managing leaks, and yet it seems I’m faced with an implacable and indestructible issue, no matter what I attempt to do.
The respawn code is as follows:
function rigSpawn(model)
local sf = model.Stats
local new = model:Clone()
sf.HP.Changed:Connect(function(amt)
if amt <= 0 then wait(2)
new.Parent = workspace; model:Destroy()
rigSpawn(new)
end
end)
end
do for _,dummy in pairs(script.Parent:GetChildren()) do
if dummy:IsA("Model") then rigSpawn(dummy) end
end
end
Maybe try disconnecting the Connection when it dies like so? (Might not be the best way but I think this’ll work, try continuing to test other various methods/disconnect other things if everything else don’t seem to work)
local Died
Died = sf.HP.Changed:Connect(function(amt)
if amt <= 0 then wait(2)
new.Parent = workspace; model:Destroy()
rigSpawn(new)
Died:Disconnect()
end
end)
Also, if you don’t mind me asking, I’m going to guess that the script above ^ is meant to detect when the humanoid dies correct? If so, why not try using Humanoid.Died instead? I might be mistaken though
I would think so as Destroy() disconnects all connections though it’s better to try than not .
Also, are you sure there aren’t any other scripts that are interacting with the dummies/other scripts that could actually be causing the Instances to go up rather than of course, the dummies? Have you made sure to isolate it to them? (TL:DR Put them in a flat baseplate and see if the same problem occurs)
In a separate place, the dummies were garbage-collected properly with no leftover memory. In the game, however, I scripted the dummies to automatically die and respawn after 5 seconds. Each cycle was the same: a spike, followed by a proportionate dip, but ever so slightly more than the original memory amount. Something within the dummies is being kept in memory when they die and are destroyed. I can’t seem to figure out exactly what.
Maybe it’s because of your wait(2). If, within the two seconds, you damage the NPC again, you’ll effectively be calling rigSpawn(new) twice. As this is recursive, the actual calls would hence keep increasing with each new call. Try printing from within the changed signal how many times it’s run.