Huge delay when player continuously uses tools

  1. I’m trying to make a sword, that a player swings, and then has a 1 second delay, and then the player is able to swing again.

  2. The delay is very large, and players can’t fire it once a second, as shown in this video:

It works the first few times, but then starts to get slower.
3. I tried removing the task.spawn, but it didn’t work. I didn’t have this issue until I put task.spawn and code to change the hit humanoids speed.

Code
--Server side
local tool = script.Parent.Parent
local canDamage = false
local canSwing = true

local player = script.Parent.Parent.Parent.Parent
local animator = player.Character.Humanoid:WaitForChild("Animator")
local swordSwing1 = animator:LoadAnimation(tool.SwordAnimation1)
local swordSwing2 = animator:LoadAnimation(tool.SwordAnimation2)

local function onTouch(otherPart)

	local humanoid = otherPart.Parent:FindFirstChild("Humanoid")

	if not humanoid then 
		return 
	end

	if humanoid.Parent ~= tool.Parent and canDamage then 
		local player = game.Players:FindFirstChild(script.Parent.Parent.Parent.Name)
		local character
		for _, v in pairs(player.characters:GetChildren()) do
			if v.Equipped.Value == true then
				character = v
			end
		end
		local hitPlayer = humanoid.Parent
		
		if hitPlayer:FindFirstChild("NPC") then
			humanoid:TakeDamage(character.MAttack.Value)
		elseif game.Players:WaitForChild(hitPlayer.Name).TeamColor == player.TeamColor then
			return false
		else
			local hitPlayer = game.Players:WaitForChild(humanoid.Parent.Name)
			local char2
			for _, v in pairs(hitPlayer.characters:GetChildren()) do
				if v.Equipped.Value == true then
					char2 = v
				end
			end
			humanoid:TakeDamage(character.MAttack.Value)
			task.spawn(function()	
				humanoid.WalkSpeed = 6
				wait(.5)
				humanoid.WalkSpeed = char2.Speed.Value
			end)
			
		end
	else
		return
	end
	canDamage = false
end

local function slash()
	if canSwing then
		local random = math.random(1,2)
		if random == 1 then
			swordSwing1:Play()
		elseif random == 2 then
			swordSwing2:Play()
		end
		canSwing = false
		canDamage = true
		wait(1)
		canSwing = true
	end
end

tool.Activated:Connect(slash)
tool.Handle.Touched:Connect(onTouch)
1 Like

Its probably something to do with the task.spawn

task.spawn(function()	
	humanoid.WalkSpeed = 6
	wait(.5)
	humanoid.WalkSpeed = char2.Speed.Value
end)

can you say what your ping is when you are slashing

My ping is only about 80-200 MS. All other stats(CPU, RAM, NETWORK) all seem to be normal as well.

Found the issue! Had to do with task.spawn messing with animations. Fixed by moving to int and bool values instead of local variables. Thanks for all the help!

1 Like

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