Is there a way to completely stop a script as its being destroyed?

So I have certain objects in my game that are periodically placed. I’m trying to have my script destroy the object once its taken enough damage. It works, however after being destroyed I’m still getting errors in my output like

14:00:42.527  Workspace.Wall.selfdelete:16: attempt to index nil with 'States'  -  Studio

Is there a way to completely stop the script as its being destroyed?

local damage = 0
script.Parent.States.iFrames.Changed:Connect(function()
	damage = damage + 1
	if damage == 1 then
		script.Parent.HumanoidRootPart.front.Transparency = 0.8
		script.Parent.HumanoidRootPart.back.Transparency = 0.8
	elseif damage == 2 then
		script.Parent.HumanoidRootPart.front.Transparency = 0.2
		script.Parent.HumanoidRootPart.back.Transparency = 0.2	
	elseif damage == 3 then
		script.Parent:Destroy()
		script:Destroy()
	end
	print("Wall damaged")
	wait(1)
	if script.Parent.States.iFrames.Value~=0 then
		script.Parent.States.iFrames.Value=0
	end
end)
script.Disabled = true

might be a good idea?

2 Likes

If you call script.Parent:Destroy() and script:Destroy() in lines 11 & 12 then how can you call if script.Parent... in line 16?
If you are destroying the Parent why would you be trying to set iFrames.Value? The Parent wouldn’t exist.

thats what i thought, but apparently not!

Unfortunately did not end up working :confused:

Try leaving out those last lines (put – in front so if there’s no change it’s easy to change back).
Or how about after the wait(1) you put if script.Parent.States == nil then return end

Have you tried using return on a new line after script:Destroy()?

elseif damage == 3 then
	script.Parent:Destroy()
	script:Destroy()
    return
end
script:Disconnect()

390

Destroying / disabling scripts in runtime isn’t advised, I highly recommend you don’t do that. There are situations where the script can stay running.

You might want to use a combination of these instead;