Issue with onTouched hit repeating too many times

Evening, developers.

I’m trying to make a script that brings the number value of my tally billboard up by one whenever an object comes into contact with it. However, I’m running into the issue where the object keeps “hitting” the detector and doesn’t stop counting upwards.

Result of script

Here’s the portion of my script that needs insight. I’ve tried messing around with some logic gates so that the block has to meet a certain requirement in order to count, but that hasn’t helped. What’s the easiest way to limit this activity to just +1 on the value?

function onTouched(hit)
game.Workspace.Statistics.SurfaceGui.Burned.BurnedValue.Value = game.Workspace.Statistics.SurfaceGui.Burned.BurnedValue.Value + 1
        game.Workspace.Statistics.SurfaceGui.Burned.Text = ("Burned: "..(game.Workspace.Statistics.SurfaceGui.Burned.BurnedValue.Value))
        game.Workspace.Statistics.SurfaceGui.Wasted.WastedValue.Value = game.Workspace.Statistics.SurfaceGui.Wasted.WastedValue.Value + 1
        game.Workspace.Statistics.SurfaceGui.Wasted.Text = ("Total Waste: "..(game.Workspace.Statistics.SurfaceGui.Wasted.WastedValue.Value))
1 Like

There are a number of ways to approach this problem, depending on your game!

  1. You can create a debounce so that your touch detection only triggers after a certain time. This would be useful if you only want one part to touch the detection at a time!
  2. You can use an attribute to mark which parts has touched the detection and which hasn’t!
  3. You can create a table that records all the parts that touches the detection and ignores if they touch the detection again (WARNING: This will create memory leaks if not done properly. Keeping a table with a bunch of references will create lots of memory)!

These solutions really depend on the nature of your game. Consider whether or not parts get destroyed when they touch the detection, whether or not parts should be counted multiple times if they the detection multiple times or only once!

For simplicity and inferring from the context of your game, I’m going to guess that these parts only need to be recorded ONCE when they touch the detection.

You can use attributes to record these touches!

function onTouched(hit: BasePart)
   -- Check if this part is a burnable part,
   -- Not something like a character's limb or something
   -- Change this for your game!
   if hit.Name ~= "Burnable" then return end 

   -- Check if this part has already been "Burned"
   if hit:GetAttribute("Burned") then return end
 
   -- Mark that it's been burned
   hit:SetAttribute("Burned", true)

   -- INSERT YOUR UPDATE CODE HERE
end
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.