I need help with an event inside an event

The script below makes it so that whenever you left-click, it’s supposedly plays an animation and hurts other players if touched. However, the Touched event always fires when I touch someone, even if I didn’t left-click. Sorry if this sounds confusing :sweat_smile:

game.ReplicatedStorage.OnClick.OnServerEvent:Connect(function(player)
	local debounce = false
	player.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.Animation):Play()
	player.Character.HumanoidRootPart.Touched:Connect(function(hit)
		if debounce == false then
			debounce = true
			local human = hit.Parent:FindFirstChild("Humanoid")
			if human then
				human:TakeDamage(math.huge)
			end
			wait(2)
			debounce = false
		end
	end)
end)

Sorry in advance if my script looks bad, I’m only a beginner

Try this instead…

game.ReplicatedStorage.OnClick.OnServerEvent:Connect(function(player)
	local debounce = false
	local animation = player.Character.Humanoid:LoadAnimation(game.ReplicatedStorage.Animation)
	animation:Play()
	local hitConnection = player.Character.HumanoidRootPart.Touched:Connect(function(hit)
		if debounce == false then
			debounce = true
			local human = hit.Parent:FindFirstChild("Humanoid")
			if human then
				human:TakeDamage(math.huge)
			end
			wait(2)
			debounce = false
		end
	end)
	animation.Stopped:Connect(function()
		hitConnection:Disconnect() --try with small "d" aswell.
	end
end)
1 Like

If your wondering what I did here…
I first made the animation as a variable so I can detect when it stops
Secondly,
I made the .touched event a variable so it can be disconnected / permanently stopped.
Thirdly,
I waited u til the animation finished playing and then disconnected the function.

1 Like

Not only has it worked, but I learned something new today. Thanks!

Your welcome! Glad I was able to help. Continue on learning, eventually, you will be something great!

animation.Stopped:Connect(function()
	animation:Destroy() --Disconnects the above event and removes the no longer needed animation track (prevents two potential memory leaks).
	hitConnection:Disconnect() --This is correct, 'disconnect' is deprecated.
end