Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How Would I Add a Debounce on a for i, v Loop?

I have Gems around my map, when you touch a gem, it's supposed to teleport underground If I add a debounce, when I touch them for the first time, it does the job well, but for the second time, nothing happens, I don't get it?

local debounce = false

for i, v in pairs(game.Workspace.GemHunt.theGems:GetChildren()) do
	v.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Humanoid") then
			if v:IsA("Part") then
				if debounce == false then
					debounce = true
				
				v.Position = v.Position + Vector3.new(0, -2, 0)
				wait(3)
				print("Coming back")
				v.Position = v.Position + Vector3.new(0, 2, 0)
				
				wait(1)
					debounce = false
				end
			end
		end
	end)
end

1 comment

0

Try doing "if debounce then return end" between lines 04 and 05.

1 answer

✓ Accepted answer

thy this: (should be working as I've tested it) :)

local Gems = {} -- store the gems in here.
for i, v in pairs(game.Workspace.GemHunt.theGems:GetChildren()) do
	-- fill up the gems table using the gem as key
	Gems[v] = {
		deBounce = false
	}
	v.Touched:Connect(function(hit)
		--// reference the correct Table entry
		local MyTab = Gems[v]
		local debounce = Gems[v].deBounce
		if hit.Parent:FindFirstChild("Humanoid") ~= nil then
           	if v:IsA("Part") then
				if(debounce == false) then
					Gems[v].deBounce = true    
					v.Position= v.Position+ Vector3.new(0, -2, 0)
                	wait(3)
	                print("Coming back")
					v.Position= v.Position+ Vector3.new(0, 2, 0)
	                wait(1)
					Gems[v].deBounce = false 
                end
            end
        end
    end)
end

The above code should work, i had mine moving the gems by CFrame but i've switched it back to Vector3

I think the reason it was only working once and not any more is because it was flipping the debounce variable to false and each new touch was keeping it as false thus disabling it. This way (in the above code) I've made it, so every Gem Part has its own deBounce switch, so it should work better with multiple touches.

Hope this helps! :)

Edited due to a little bug with the debounce variables not being set correctly

Duh@me lol xD

1 comment

0

Thank you so much, the Script works fine now!

This discussion is preserved as it was. New answers, comments, and votes are closed.