Help with mouse activated spam

Hello there.

For my horror game i have been trying to create a battery system for my flashlight item. I’m using tool.Activated to achieve the goal of the system. However i have a problem when if you spam click the flashlight it make the battery decrease faster because of the coroutine is being called each click. Is there a way i could fix it?.

Script:

local BatteryValue = script.Parent:WaitForChild("BatteryValue")

script.Parent.Activated:Connect(function()
	if script.Parent.Handle.SpotLight.Enabled == true then
		script.Parent.Handle.SpotLight.Enabled = false
		script.Parent.Handle.Sound:Play()
		game.Lighting.FogEnd = 40
		script.Parent.IsOn.Value = false
	else
		if BatteryValue.Value >= 1 then
			script.Parent.Decreasing.Value = true
			script.Parent.Handle.SpotLight.Enabled = true
			script.Parent.IsOn.Value = true
			
			coroutine.wrap(function()
				while task.wait(.2) do
					if script.Parent.IsOn.Value == true and BatteryValue.Value ~= 0 then
						BatteryValue.Value -= 2
						print(BatteryValue.Value)
					end
				end
			end)()

			script.Parent.Handle.Sound:Play()
			game.Lighting.FogEnd = 72
		else
			script.Parent.Handle.SpotLight.Enabled = false
		end
	end
end)

Any help is appreciated.

1 Like

Move the while loop outside of the function, so another loop isn’t being created each time the tool is clicked. The activated function should more or less just tell the loop the state of the flashlight.

1 Like

You need a debounce in the .Activated function to check if it’s been clicked already.

Why not try this in the function instead of your if BatteryValue.Value >= 1 then

		while BatteryValue.Value >= 1 then
			script.Parent.Decreasing.Value = true
			script.Parent.Handle.SpotLight.Enabled = true
            task.wait(2)
			BatteryValue.Value -= 2
			print(BatteryValue.Value)
		end
			script.Parent.Handle.Sound:Play()
			game.Lighting.FogEnd = 72

You can also get rid of your
script.Parent.IsOn.Value = false
and just use the value of
script.Parent.Handle.SpotLight.Enabled = false
since it’s doing the exact same thing.

This work thank you. I didn’t realise that i haven’t move the while loop lol

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