Why does this script print multiple times?

So this script is supposed to trigger when the player hits it and is supposed to make a value true and then print out something (This print is gonna get replaced later, for now its just a test) and here is where i get this issue which is the fact that it always gets printed 16 times which is not good because its supposed to only get printed once.

the script:
script.Parent.Touched:Connect(function(Object)
if Object.Parent:FindFirstChild(“Humanoid”) and Object.Parent:FindFirstChild(“Humanoid”).Sit
== true and Object.Parent.HumanoidRootPart.Velocity.Magnitude >= 100 then
wait(1)
script.Parent.HitAlready.Value = true
wait(1)
if script.Parent.HitAlready.Value == true then
wait(1)
print(“speedtrap hit by player”)
wait(15)
script.Parent.HitAlready.Value = false
end
end
end)

1 Like

It runs every time the character is on the part

well, i know that, and thats what i`m trying to fix but dont know how

.Touched is handled in a very inefficient way.

The first time the player touches the part, Touched is fired. Once they move, TouchEnded and then subsequently Touched is once again fired. For this reason, you need to add a better debounce, i.e:

local db = false

script.Parent.Touched:Connect(function(obj)
   if obj and Object.Parent:FindFirstChild(“Humanoid”) and obj.Parent[“Humanoid”].Sit == true and obj.Parent.HumanoidRootPart.Velocity.Magnitude >= 100 then\
      if not db then
         db = true
         -- Run necessary code
         db = false
      end
   end
end)
3 Likes

Try using a debounce, the event probably is firing for multiple body parts.

2 Likes

Thanks, that did solve the issue! :slight_smile:

One more question though: how do i make it modify an IntValue inside of the player thats in ‘Players’? Since this script is getting the player from workspace

You can use

player = game.Players:GetPlayerFromCharacter(object.Parent)