Help with touch function

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? I want to create a function that when the player touches the fire sphere he takes 5 ticks of damage and then waits 5 seconds for the function to work again

  2. What is the issue? The problem is that when I do this it ends up spamming the function several times

  3. What solutions have you tried so far? I tried on the dev forum but it doesn’t seem to have the same problem that I

Here is my code

	
    powerRange.Touched:Connect(function(hit)
		
		print("A")
		
		if damaged == false then
	damaged = true
		
		local hum = hit.Parent:FindFirstChild("Humanoid")
		
		if hum then
			
			hum.Health = -10
			task.wait(1)
			hum.Health = -10
			task.wait(1)
			hum.Health = -10
			task.wait(1)
			hum.Health = -10
			task.wait(1)
			hum.Health = -10
		end
		
		hit.Color = Color3.new(1, 0.917647, 0.027451)
		hit.Material = Enum.Material.Neon
    end

	 task.wait(5)
	 damaged = false
	end)```

Please do not ask people to write entire scripts or design entire systems for you. If you can't answer the three questions above, you should probably pick a different category.

A more optimized way of repeatedly executing the same task is using a for loop

In this case that would look like:

	for i = 1, 5 do -- 5 times
		hum.Health -= 10
		task.wait(1)
	end

Still, the function is being spammed, even though it has the for loop, I don’t understand it since I added a wait

I believe your issue is not defining damaged beforehand since everything else in your code appears to work. I would be able to properly diagnose it if you had screenshots of your output if this doesn’t work.

local damaged = false

powerRange.Touched:Connect(function(hit)
		
		print("A")
		
if damaged == false then
	damaged = true
		
		local hum = hit.Parent:FindFirstChild("Humanoid")
		
		if hum then
			for i = 1, 5 do -- 5 times
		hum.Health -= 10
		task.wait(1)
	end
		end
		
		hit.Color = Color3.new(1, 0.917647, 0.027451)
		hit.Material = Enum.Material.Neon
    end

	 task.wait(5)
	 damaged = false 
end)

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