Help with stopping a thread from running entierly

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

  1. What do you want to achieve? Keep it simple and clear!
    So, I have this flashlight system with animations and turning the flashlight on and off. However i want to have it so that if you have the flashlight turned off for a set amount of time, an animation of putting down your arm with the flashlight will play.

  2. What is the issue? Include screenshots / videos if possible!
    Most of the time if you turn on your flashlight before the time is over, it will turn it on then after the timer is done, put down the flashlight even though it’s turned on.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve tried having the function in a task.spawn so that i could task.cancel the function when the flashlight is turned on after the put down animation or just generally turning on the flashlight, and i’ve also tried coroutine.close, but neither seem to work.

Here’s the current function containing the stall function (this is not the full code by the way.):

local Stall

local function ToggleFlashlight()
	if not Yield then
		Yield = true
		if Flashlight:GetAttribute("Enabled") == false then
			print(Flashlight:GetAttribute("Enabled"))
			local WasStalling = false
			
			for _, Animation in Flashlight.Parent.Humanoid:GetPlayingAnimationTracks() do
				if Animation.Name == "IdleOff" then
					WasStalling = true
				end
			end
			
			for _, Animation in Animations do
				Animation:Stop()
			end
			
			if WasStalling then
				Animations["Equip"]:Play()
				task.wait(Animations["Equip"].Length)
			end
			
			Animations["Toggle"]:Play()
			Animations["Toggle"]:GetMarkerReachedSignal("Toggle"):Once(function()
				LightItemModule:ToggleLightItem(Flashlight, true)
				Sounds.TurnOn:Play()
				print("played on")
			end)
			
			task.wait(Animations["Toggle"].Length)
			Animations["IdleOn"]:Play()
			Flashlight:SetAttribute("Enabled", true)
			
			task.wait(0.25)
			Yield = false
		elseif Flashlight:GetAttribute("Enabled") == true then
			print(Flashlight:GetAttribute("Enabled"))
			for _, Animation in Animations do
				Animation:Stop()
			end

			Animations["Toggle"]:Play()

			Animations["Toggle"]:GetMarkerReachedSignal("Toggle"):Once(function()
				LightItemModule:ToggleLightItem(Flashlight, false)
				Sounds.TurnOff:Play()
				print("played off")
			end)

			task.wait(Animations["Toggle"].Length)
			Animations["IdleOn"]:Play()
			Flashlight:SetAttribute("Enabled", false)

			task.wait(0.25)
			Yield = false

			task.wait(1)
			Stall = task.spawn(function()
				Animations["IdleOn"]:Stop()
				Animations["UnEquip"]:Play()
				task.wait(Animations["UnEquip"].Length)
				Animations["IdleOff"]:Play()
			end)
		end
	end
end

Flashlight.Activated:Connect(ToggleFlashlight)
1 Like