Scripting Book/Chapter 6
Introduction
Hello again! This time we're going to learn about debounce and what it is used for.
Debounce allows a function to be fired once and cannot be fired again for a period of time.
What is debounce?
Debounce is a variable, it doesn't have to be called debounce. It can be anything you want. But we're going to stick with debounce.
What kind of variable is debounce?
Debounce can be any kind of variable you want, it is commonly used a Boolean.
What is debounce used for?
Debounce is used in things such as regen scripts.
Creating the code
The first line
As debounce is a variable we need to index it by writing a simple line of 'debounce = false'.
debounce = false
The installation
Now we need to start the function. Last time when we made a script that when you hit an object that the script was inside it a message appeared saying 'Howdy, y'all!' but you may have noticed it made a lot of lag and the screen was full of these messages.
That's where debounce comes in handy! Let's pull out the script we made last time:
function onTouched() m = Instance.new("Message", game.Workspace) m.Text = "Howdy, y'all!" wait(5) m:Remove() end script.Parent.Touched:connect(onTouched)
Now add the debounce variable,
debounce = false function onTouched() m = Instance.new("Message", game.Workspace) m.Text = "Howdy, y'all!" wait(5) m:Remove() end script.Parent.Touched:connect(onTouched)
Next, after the function is declared we need to check that debounce's value is not true. If it is true then return to the start of the function and try again.
debounce = false function onTouched() if debounce == true then return end m = Instance.new("Message", game.Workspace) m.Text = "Howdy, y'all!" wait(5) m:Remove() end script.Parent.Touched:connect(onTouched)
After that 'if' statement we need to make the value of debounce to true.
debounce = false function onTouched() if debounce == true then return end debounce = true m = Instance.new("Message", game.Workspace) m.Text = "Howdy, y'all!" wait(5) m:Remove() end script.Parent.Touched:connect(onTouched)
One more thing to do to this script to finish installing the debounce is before the 'end' and after the line where the message is removed. We need to make debounce false again.
The finished script
debounce = false function onTouched() if debounce == true then return end debounce = true m = Instance.new("Message", game.Workspace) m.Text = "Howdy, y'all!" wait(5) m:Remove() debounce = false end script.Parent.Touched:connect(onTouched)
And we're done! Congratulations!