How do I make this reload script less hacky

So whenever the player reloads their gun, the script waits until however long it takes to reload, and then it checks if the player unequipped their gun during this time. If they did, then the script doesn’t add ammo to the gun and basically cancels the reload.

The way I track this is with a number, which I increase by 1 every time the gun is unequipped, and then to check if the gun was unequipped while reloading, I check if this number is different than at the start of the reload.

It feels like a hacky solution and I wanted to know if there was a better way to check if the gun was unequipped while reloading.

local UnequipCounter = 0

local function Reload()
	ReloadAnimation:Play()
	
	local CurrentUnequipCounter = UnequipCounter
	
	task.delay(ReloadTime, function()
		if CurrentUnequipCounter == UnequipCounter then
			Ammo = MagazineCapacity
		end
	end)
end

Tool.Unequipped:Connect(function()
	ReloadAnimation:Stop()
	UnequipCounter += 1
end)

–Assume Tool is the tool

ToolEquipped = false

function Toggle()
	ToolEquipped = not ToolEquipped
end

Tool.Equipped:Connect(Toggle)
Tool.Unequipped:Connect(Toggle)

The thing is that if the tool was unequipped and then quicky equipped again, once the script finishes waiting it’ll only see that the tool is equipped and continue the reload, even though the tool was unequipped

I’m looking for a way to detect if it was unequipped while reloading without having to use a counter

Nevermind I found a solution

local Thread

local function Reload()
	ReloadAnimation:Play()

	Thread = task.delay(ReloadTime, function()
		Ammo = MagazineCapacity
	end)
end

Tool.Unequipped:Connect(function()
	ReloadAnimation:Stop()

	if Thread then
		task.cancel(Thread)
	end
end)
2 Likes

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