Im trying to make battleground m1 system but punch loop is sometimes is happening multiple times

also im wondering if there a better way of knowing if a player is holding with context action service

local CAS = game:GetService("ContextActionService")

local Remote = game.ReplicatedStorage.Events.RemoteEvent

local character = script.Parent
local Humanoid = character:WaitForChild("Humanoid")

local player = game.Players:GetPlayerFromCharacter(character)

local punchAnim: Animation = Instance.new("Animation")
punchAnim.AnimationId = "rbxassetid://70425885769525"
punchAnim.Parent = script.Parent

local CanPunch = true

local keybind = Enum.UserInputType.MouseButton1

local Holding = false

local PunchesPerCombo = 4
local PunchCount = 0

local EndTime = 2

local function Punch(ActionName, inputState)
	if ActionName == "punch" and inputState == Enum.UserInputState.Begin then
		Holding = true
		local animator = Humanoid:FindFirstChildOfClass("Animator")

		task.spawn(function()
			while Holding do
				if not CanPunch or character:GetAttribute("Dashing") == true then
					task.wait(0.1)
					continue
				end

				CanPunch = false
				if not animator then
					animator = Instance.new("Animator")
					animator.Parent = Humanoid
				end

				local AnimationTrack: AnimationTrack = animator:LoadAnimation(punchAnim)
				AnimationTrack:Play()
				task.spawn(function()
					task.wait(0.2)
					Remote:FireServer()
				end)

				PunchCount += 1

				if PunchCount >= PunchesPerCombo then
					CanPunch = false
					print("starting end time")
					task.wait(EndTime)
					print("Punches reset")
					CanPunch = true
					PunchCount = 0
				end

				task.wait(0.6)
				print("Ended")
				CanPunch = true
			end
		end)

	elseif inputState == Enum.UserInputState.End then
		Holding = false
	end
end

CAS:BindAction("punch", Punch, true, keybind)
CAS:SetTitle("punch", "Punch")
CAS:SetPosition("punch", UDim2.new(0.2, 0, 0.4, 0))
1 Like