Flashlight Battery Script Not Working

I’m making a flashlight tool script that has an intvalue named ‘Battery’ that’s supposed to drain after every second only when the flashlight is turned on, if it’s off, the battery stops draining.

I’m not sure what I’m doing wrong, but the Battery value is not decreasing when i turn the flashlight on, it just stays at it’s starting value which is 100.

local flashlight = script.Parent
local beam = flashlight.LightHandle.LightEffect
local part = flashlight.LightPart
local battery = flashlight:FindFirstChild("Battery")
local clicksound
local on = false
local cd = 0.4

local function On()
	on = true
	beam.Enabled = true
	part.Material = Enum.Material.Neon
	part.Spotlight.Enabled = true
end

local function Off()
	on = false
	beam.Enabled = false
	part.Material = Enum.Material.Metal
	part.Spotlight.Enabled = false
end

flashlight.Activated:Connect(function()
	if battery.Value > 0 and on == false then
		On()
	elseif battery.Value > 0 and on == true then
		Off()
	end
end)

flashlight.Unequipped:Connect(function()
	Off()
end)

while true do
	task.wait(1)
	if battery.Value <= 0 then
		Off()
	end
end

while on == true do
	battery.Value = battery.Value - 1
	task.wait(1)
end

Any help is appreciated.

Instead of having 2 while loops, which won’t work unless on different threads btw, just add an if statement in the first loop to check if on is true

i am pretty sure it is because the script stays on the first loop and never reaches the second loop, just do one loop

while true do
    task.wait(1)
    if battery.Value <= 0 then
         Off()
    end
    if on == true then
       battery.Value = battery.Value - 1
    end
end

i feel stupid now, but it works, so thanks.

1 Like