I am creating a laser projectile, but there’s a problem: I cannot destroy the laser.
I open the dev console and it said:
Workspace.laser.laserTouched:8: attempt to index nil with ‘Destroy’
I don’t get why I am getting this error.
script.Parent.Touched:Connect(function(hit)
if hit.Name ~= "laser" and hit.Name ~= "Body" and hit.Name ~= "Right Arm" then
script.Parent:Destroy()
end
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health -= 20
hit.Parent.Humanoid.Sit = true
script.Parent:Destroy() -- Here is the error
end
end)
:Remove() removes it from the datamodel by setting the parent to nil. It requires passive garbage collection to remove from memory. If you have a reference to it anywhere, it will remain.
:Destroy() also locks the Parent and destroys connections and calls. It is more complete.
I have had similar issues with :Destroy() with touched events. It ended up being a race condition. The server was trying to destroy the same object multiple times and of course that can only be done once.