Help with Combat Stun System

Currently for my combat system, I have a module called StunHandler that is supposed to stun the specified character for a specific amount of time.

However there is a problem when you try to stun a character multiple times. For example, when I hit a target character one time, the script works perfectly and the target character is stunned for lets say 1 second. But if I were to hit the target character with a 5-hit combo, the StunHandler module is supposed to keep that target character stunned until the combo ends.

My script however, doesn’t do this and the target character sometimes gets un-stunned in the middle of a 5-hit combo

Here is the code below:

local StunHandler = {
	stunnedCharacters = {
		
	}
}

function StunHandler.create(target : Model, time)
	if StunHandler.stunnedCharacters[target] then return end
	
	StunHandler.stunnedCharacters[target] = {
		model = target;
		connections = {};
		elapsedTime = tick();
	}
	
	StunHandler.stunnedCharacters[target].model:SetAttribute("Stunned", true)
	StunHandler.stunnedCharacters[target].model.PrimaryPart.Anchored = true
	
	local highlight = Instance.new("Highlight", target) 
	highlight.FillTransparency = .5
	
	StunHandler.stunnedCharacters[target].connections.connect = target:GetAttributeChangedSignal("Stunned"):Connect(function()
		if not target:GetAttribute("Stunned") then
			target:FindFirstChildWhichIsA("Highlight", true):Destroy()
			target.PrimaryPart.Anchored = false
			
			for _, connection in StunHandler.stunnedCharacters[target].connections do
				connection:Disconnect()
			end
			
			StunHandler.stunnedCharacters[target] = nil
		end
	end)
	
	task.delay(time, function() StunHandler.stunnedCharacters[target].model:SetAttribute("Stunned", false) end)
end

return StunHandler

I think you shouldn’t set a specific time when the stun ends, like you’re doing with the task.delay. Instead, you should have code in a separate thread that constantly checks the remaining time, then un-stuns the character and closes the thread. With this, when you add a stun, you could increment the time, allowing you to stun the other character for longer

I feel that the connections part overcomplicates things here. Most games settle for a simple solution such as having a value change when a stun function is called, then check at the end of the stun if another stun happened. Like this:

StunCount = 1

function beStunned(Time)
	StunCount += 1
	CurrentCount = StunCount
	IsStunned = true
	
	task.wait(Time)

	if CurrentCount = StunCount then
		IsStunned = false
	end
end