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
for _, Parts in pairs (Sword:GetChildren()) do Parts.Touched:connect(function(part) print(part) end) end
You'll want to add a Debounce to your script. An easy way to do this is as follows.
local debounce = false --Any variable connected to a Boolean value can be used for _, Parts in pairs (Sword:GetChildren()) do Parts.Touched:connect(function(part) if part and not debounce do --Checks if debounce is false and if part exists for... reasons debounce = true --Sets the debounce variable to true so the first conditional cannot fire print(part) --Code wait(2) --Can be any amount of time debounce = false --Sets debounce back to false so the conditional can fire again end) end end
Important things to note are that any Boolean connected variable can be used, and you can invert the way the variables act.
local debounce = true --Within function-- if firstConditional and debounce then --Simply checks if debounce is true instead of false --Fluff wait(2) --Needs a wait otherwise the function would fire all at once debounce = true 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:
script.Parent.Touched:connect(function(Part) Part.BrickColor=BrickColor.new("Really black") 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.
isfirst=false script.Parent.Touched:connect(function(Part) if isfirst==false then isfirst=true Part.BrickColor=BrickColor.new("Really black") end 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.