There are multiple parts in a model called 'Sword' and I want to print the part it touches when the Touched Function is fired. It does do this however it prints it multiple times and this is not what I want. So how do I make the Touched function only fire once instead of multiple times?
Output as the touch function is repeatedly fired: Output
1 | for _, Parts in pairs (Sword:GetChildren()) do |
2 | Parts.Touched:connect( function (part) |
3 |
4 | print (part) |
5 |
6 | end ) |
7 | end |
You'll want to add a Debounce to your script. An easy way to do this is as follows.
01 | local debounce = false --Any variable connected to a Boolean value can be used |
02 |
03 |
04 | for _, Parts in pairs (Sword:GetChildren()) do |
05 | Parts.Touched:connect( function (part) |
06 | if part and not debounce do --Checks if debounce is false and if part exists for... reasons |
07 | debounce = true --Sets the debounce variable to true so the first conditional cannot fire |
08 | print (part) --Code |
09 | wait( 2 ) --Can be any amount of time |
10 | debounce = false --Sets debounce back to false so the conditional can fire again |
11 | end ) |
12 | end |
13 | end |
Important things to note are that any Boolean connected variable can be used, and you can invert the way the variables act.
1 | local debounce = true |
2 |
3 | --Within function-- |
4 | if firstConditional and debounce then --Simply checks if debounce is true instead of false |
5 | --Fluff |
6 | wait( 2 ) --Needs a wait otherwise the function would fire all at once |
7 | debounce = true |
8 | end |
If you have any other questions (Or my raw code derps out) Feel free to leave a comment or Roblox PM~
~MBacon15
You can easily do this using variables. Just take a look at this:
1 | script.Parent.Touched:connect( function (Part) |
2 | Part.BrickColor = BrickColor.new( "Really black" ) |
3 | end ) |
This script will change one part's BrickColor to "Really black". But if we want only the first touched part to change, we can add a debounce using variables.
1 | isfirst = false |
2 | script.Parent.Touched:connect( function (Part) |
3 | if isfirst = = false then |
4 | isfirst = true |
5 | Part.BrickColor = BrickColor.new( "Really black" ) |
6 | end |
7 | end ) |
Now if the part was touched, it will change the variable to true and disable the script from getting past the if. I hope this helped! If you got any questions, feel free to ask.