Trying to make onTouched function run once

I’m making a game that’s kinda like a tycoon. Instead of drops, it’s different objects with different values. There’s an int value inside each object. When it touches a certain part, it adds the value of the object to another int value. I want it to add only once, but it runs the script multiple times and gives a ton of money.

local eater = script.Parent
local MoneyValue = game.StarterGui.Money.money

function onTouched(obj)
	print("Object touched")
	wait(1)
	obj:ClearAllChildren()
	wait(2)
	obj:Destroy()
	
	local addValue = game.ReplicatedStorage.SelectedObject:GetChildren()
	
	for i,v in addValue do
		local value1 = v:FindFirstChild("Value")
		MoneyValue.Value += value1.Value
	end
	
end

eater.Touched:Connect(onTouched)
2 Likes

Try adding a debounce like this:

local db = false
local eater = script.Parent
local MoneyValue = game.StarterGui.Money.money

function onTouched(obj)
     if db == true then return end
     db = true
	print("Object touched")
	task.wait(1)
	obj:ClearAllChildren()
	task.wait(2)
	obj:Destroy()
	
	local addValue = game.ReplicatedStorage.SelectedObject:GetChildren()
	
	for i,v in addValue do
		local value1 = v:FindFirstChild("Value")
		MoneyValue.Value += value1.Value
	end
	db = false
end

eater.Touched:Connect(onTouched)

I managed to fix the problem seconds before you replied. But my solution was close to your’s.
I just added a boolean value to the object. Thanks anyway!

Yea no worries just make sure a to mark a solution.

You can learn more about the Importance of Debounces here and how they can be properly used on the Roblox docs page if you like:

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