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

How Do You Do This Touch Function?

How do you cause the part to do something the first time it's touched, but when you touch it again it does something else, then it does the first action again, and so on in only one script? Thanks!

local debounce = false

function onTouched()	
	if not debounce then
		debounce = true
		--code
		function onTouched() -- lol I tried this to see if it works, but it didn't
			--code
		end
		debounce = false
	end
end

script.Parent.Touched:connect(onTouched)

3 comments

0

Do you want it to repeat that next action every time after the first action?

0

I want it to do the first action, then when it is touched again, it does the second action, and then repeats. So it goes back to action 1.

0

You could put it in a while loop and wait on the event to occur. In order to get information from events, set variables on the event such as PartThatHit = Part.Touched:wait() Try: while wait() script.Parent.Touched:wait() --Code Here script.Parent.Touched:wait() --Second Code Here end

1 answer

✓ Accepted answer

Just use a boolean value.

local bool = false

local function onTouched(hit)
	if bool then
		bool = false
		
		-- Do something...
	else
		bool = true
		
		-- Do something else...
	end
end


part.Touched:connect(onTouched)

Additionally, you could shorten your code by replacing bool = false and bool = true with a single bool = not bool before the if ... else ... end block. That would flip bool's value whatever its previous value was.

3 comments

0

Sorry I tried this, but it didn't work for me.

0

Oh sorry, I read your question too fast. I'll update my answer.

0

Thanks it worked!

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