I'm currently making a sword right now, and everything works perfectly fine, except that if the blade of the sword touches an NPC, it does damage. I only want it to do damage when it is left-clicked with the mouse. Please help!
Local Script:
local CanAttack = true local player = game.Players.LocalPlayer local char = player.Character or player.CharacterAdded:Wait() local idle = char:WaitForChild("Humanoid"):LoadAnimation(script.idle) local attack = char:WaitForChild("Humanoid"):LoadAnimation(script.attack) script.Parent.Equipped:Connect(function(mouse) idle:Play() mouse.Button1Down:Connect(function() if CanAttack then idle:Stop() attack:Play() CanAttack = false idle:Play() wait(1) attack:Stop() CanAttack = true script.Parent.CanDamage.Value = true end end) end)
My other Local Script:
script.Parent.Equipped:Connect(function(mouse) mouse.Button1Down:Connect(function() script.Parent.blade.Touched:Connect(function(p) if script.Parent.CanDamage.Value == true then p.Parent.Humanoid:TakeDamage(20) script.Parent.CanDamage.Value = false wait(1) script.Parent.CanDamage.Value = true end end) end) end)
First thing: Tool.Activated fires whenever the player clicks, both on local and server scripts, meaning that you can put most of your code into a server script. https://developer.roblox.com/en-us/api-reference/event/Tool/Activated
Second: because you are damaging inside a local script, the effect only happens on your screen and not theirs, like Killerbreden and kkkeelan999 said.
Third: like kkkeelan said, candamage is never set to false, meaning that it will always damage.
I'm not entirely sure, but to me, it looks as though you have CanDamage to true almost constantly.
In this section of code, after the player has been inflicted with damage, it sets CanDamage to false, meaning it can't damage anymore. But. Then there's a wait(1) followed by CanDamage being set to true. Like I said, I'm not 100% if this is it, as Idk what else is going on in your game, but if nothing else changes it, this could be the problem.
script.Parent.blade.Touched:Connect(function(p) if script.Parent.CanDamage.Value == true then p.Parent.Humanoid:TakeDamage(20) script.Parent.CanDamage.Value = false wait(1) script.Parent.CanDamage.Value = true end end)
Edit: Also, as Killerbrenden said in a comment to your post, the damaging part should be in a server script. This can be done pretty easily through remote events.