Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I stop a "touch" function after being touched?

I have this script that I just added touch function in. But when first touch it keeps being removed when spawned.

How do I stop the "touch" function after being touched?

Script: (Normal)

model = script.Parent


backup = model:clone()

script.Parent.Touched:connect(function(part)
	while true do
		wait(part)
	
	
		model:remove()

		wait(math.random(7,23))
	
		model = backup
		model.Parent = game.Workspace
		model:makeJoints()
	end
end)

2 answers

✓ Accepted answer

Hey there! You can add debounces, for more info on debounces click this link below;

http://wiki.roblox.com/?title=Debounce

Now I will help you edit your script;

model = script.Parent 
backup = model:clone()
local Cloning = false -- This is our debounce variable 

model.Touched:connect(function(part) -- When you have a variable with script.Parent just say the model
    if not Cloning then --If cloning is false then 
	Cloning = true --Set Cloning to true
    	while true do
     	   wait(part)
 
 
        	model:remove()
 
       	 	wait(math.random(7,23))

        	model = backup
        	model.Parent = game.Workspace
        	model:makeJoints()
		if Cloning then return end -- If cloning is true then return and end the script
	end
    end
end)

This script SHOULD function only once. If you want this function to function again then simply add a wait() and set Cloning back to false.

If helped in anyway please Upvote and Accept Answer

2 comments

0

Ok thanks, good to know it worked

0

It helped and didn't made it. Which is actually what it is supposed to be. Now it works.

The reason your code keeps repeating is because of your while loop on line 7. Remove that if you don't want the model to continually regen.

To stop the Touched event's signal, you can use the Disconnect function of the Touched event's RBXScriptConnection.

Usage;

local model = script.Parent
local backup = model:clone()
local TouchedConnection
--^Predefine a connection var so we can access it inside the event

TouchedConnection = script.Parent.Touched:connect(function(part)
	model:Destroy() --Remove is deprecated!
	wait(math.random(7,23))
	model = backup
	backup = model:Clone() --reset the backup var so it can be used again
	model.Parent = game.Workspace
	model:makeJoints()
	TouchedConnection:Disconnect() --Disconnect signal
end)

Alternative methods to stopping the Touched event's signal would be:

    1. Destroying the script: script:Destroy()
    1. Adding a debounce

2 comments

0

I wanted it to come back every time you touch it.

1

Then why is your question asking how to STOP the touch function after touching

This discussion is preserved as it was. New answers, comments, and votes are closed.