It doesn’t work for me and “clone” got a warning maybe because it has no event.
Let’s say I make a part which has a Clickdetector and cycles the scripts back and forward.
(Like you said Script1 is the parent of Script2 and if the part was clicked they swap places over and over.)
I got a small code written for Clickdetector:
local part = script.Parent
local click = part.ClickDetector
local function onClick(###) --Some name inside
-- whatever happens here
end
click.MouseClick:Connect(onClick)
That would help understand it better and using it in future.
local target = --path to your script
--assuming the parent remains the same and won't be destroyed, else the script will get more complicated
local parent = target.Parent
function onDestroy()
target = target:Clone()
--art of recursion
target.Destroying:Once(onDestroy)
target.Parent = parent
end
target.Destroying:Once(onDestroy)
This works within the script as well:
--self reviving script, prints "hello" every 2 seconds
script.Destroying:Once(function()
script:Clone().Parent = script.Parent
end)
--basically your code goes here
print("hello")
task.wait(2)
script:Destroy()
Keep in mind these scripts don’t handle script.Parent = nil, script.Enabled = false, script.Disabled = true and script:Remove()(because remove sets the parent of the instance and all its descendants to nil). Although it handles game.Debris:AddItem(script) because I assume it either calls Destroy() internally or fires the Destroying event manually copying the behavior of the destroy function.