You read the title, I want to make a sword in a way that the sword will only damage another player if it’s swung by the holder, but I’m not sure of how could I enabled a Touched event only during the tool’s activation.
I made a prototype script of how would it work:
local tool = script.Parent
local handle = tool:WaitForChild("Handle")
local canDamage = true
tool.Activated:Connect(function()
if not canDamage then
canDamage = false
handle.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
player.Character.Humanoid:TakeDamage(10)
end
end)
task.wait(1)
canDamage = true
end
end)
I’m not sure I completely understand, but I can tell you about the :Disconnect() method.
If you make a global value that will serve as the value of the connection, you can connect and disconnect it whenever called.
For example:
local tool = script.Parent
local handle = tool:WaitForChild("Handle")
local canDamage = true
local connection --//This will be the global value for the connection
tool.Activated:Connect(function()
if not canDamage then
canDamage = false
connection = handle.Touched:Connect(function(hit) --//Establish the connection
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
player.Character.Humanoid:TakeDamage(10)
end
end)
task.wait(1)
canDamage = true
end
end)
tool.Deactivated:Connect(function()
connection:Disconnect() --//When tool unequipped, abolish the connection
end)
Now what is happening, is when the player equips the tool, it will use the connection variable to make the tool’s Handle have a .Touched event. When the player unequips the tool, it will use the :Disconnect() function to cancel any connections made to the connection variable, thus no .Touched events being executed anymore.
There’s a chance that the ‘canDamage’ is not allowing the connection to be made before it tries to disconnect.
Maybe first setting the connection will help fix the issue?
local tool = script.Parent
local handle = tool:WaitForChild("Handle")
local canDamage = true
local connection --//This will be the global value for the connection
tool.Activated:Connect(function()
connection = handle.Touched:Connect(function(hit) --//Establish the connection
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player and canDamage then
player.Character.Humanoid:TakeDamage(10)
canDamage = false
end
task.wait(1)
canDamage = true
end)
end)
tool.Deactivated:Connect(function()
connection:Disconnect() --//When tool unequipped, abolish the connection
end)
That is because tool.Deactivated fires after the mouse button goes up.
tool.Activated:Connect(function()
if not canDamage then
canDamage = false
local connection = handle.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
player.Character.Humanoid:TakeDamage(10)
end
end)
task.wait(1)
connection:Disconnect()
canDamage = true
end
end)