Flashlight draining battery script not working

I want to make a system for my flashlight that whenever you hold it every 5 seconds or so it drains 1% of it’s battery.

The issue is that whenever you unequip the tool and reequip it, it drains twice as fast

holding = false
battery = 100
speed = 5 -- speed at which the battery will be drained

script.Parent.Equipped:Connect(function()
	holding = true
	while true do
		if holding == true then
			battery = battery - 1
			script.Parent.ToolTip = "Battery left: " .. battery
			print("Lowered Battery")
			print("holding")
			wait(speed) -- drained 1% of battery each 5 seconds
		end
		task.wait()
	end
end)

script.Parent.Unequipped:Connect(function()
	holding = false
end)

Can someone help? I’ve been looking through this and can’t figure anything out.

2 Likes

Change the condition of the while loop to holding.

script.Parent.Equipped:Connect(function()
	holding = true
	while holding do
		battery = battery - 1
		script.Parent.ToolTip = "Battery left: " .. battery
		print("Lowered Battery")
		print("holding")
		task.wait(speed) -- drained 1% of battery each 5 seconds
	end
end)

With the way you’ve set this up, every time you equip the tool it runs the draining loop. You only want the loop to run once, so run it outside of the events and have the equipped and unequipped events simply set the holding variable.

1 Like

i feel so stupid now, thank you so much!

1 Like

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