How would I make a script do something after it is destroyed?

Y’know how RemoteEvents can only fire from Local to Server and Server to Local? It’s just that but the opposite. BindableEvents can only fire from like-to-like, so only Server to Server and Local to Local.

I usually use them for ModuleScript-like behavior but when using a ModuleScript is too excessive.

Omg I wish I knew this sooner. I have needed this behavior in the past but had to just use modulescripts

1 Like

yeah modulescripts are kinda evil LMAO

Perhaps get a script that controls the effects, and set the parent to the main script. Once the player consumes the item, the effect script will be cloned into the player, and then afterwards, you’ll be free to delete the script.

Make sure at first the effect handler script is disabled, and then reenable the handler within the main script.

So the tree would look like:
Consumable Item → Main Script → Effect Script (Disabled)

There are definitely better alternatives though.

Create a ModuleScript under ReplicatedStorage called RunOnDestroy

Put this in the ModuleScript

local Uncon = Instance.new("BindableEvent")

local function runOnDestroy(object: Instance, runfunc)
	Uncon:Fire(object, runfunc)
end

Uncon.Event:Connect(function (object: Instance, runfunc)
	object.Destroying:Once(runfunc)
end)

return runOnDestroy

In an ordinary script, put something like this:

local onDestroyFunc = require(game:GetService("ReplicatedStorage"):WaitForChild("RunOnDestroy"))

onDestroyFunc(script, 
	function() 
		for i = 1, 10 do 
			print("I'm dying") 
		end 
	end)

wait(10)

script:Destroy()

That should work, remember to treat the required module as a function.

Hope this helps!

Use the ChildRemoved event from another script to detect when the script is destroyed

Hey @Khookins, if you have found the solution, please mark any of the replies as solution, if not please explain what is wrong with them.

1 Like

I am unsure what of these solutions to mark as they are all viable but I’m not sure which one is the best

Whichever one helped the most is what you should mark.