I created a katana, and when the player clicks it deals damage, it should stop dealing damage to things it touches when the player is not slashing, for some reason it still does even after I disconnect the function.
Here’s my code:
wait(1)
local Remote = script.Parent.Katana_Remote
local Tool = script.Parent
local Blade = script.Parent.Blade
local BladeHit
Remote.OnServerEvent:Connect(function(playerWhoFired)
Tool.Activated:Connect(function()
BladeHit = Blade.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid ~= Tool.Parent.Humanoid then
hit.Parent.Humanoid:TakeDamage(10)
end
wait(1)
BladeHit:Disconnect()
end)
end)
end)
Remote.OnServerEvent:Connect(function(playerWhoFired)
BladeHit = Blade.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid ~= Tool.Parent.Humanoid then
hit.Parent.Humanoid:TakeDamage(10)
end
end)
wait(1)
BladeHit:Disconnect()
end)
local touchedConnection = nil
local attacking = false
local debounce = {}
-- this function will damage characters by 10 when it hits any of there character parts
local function Touched(touchedPart)
local humanoid = touchedPart.Parent:FindFirstChild("Humanoid")
if humanoid == nil then return end
if humanoid == Tool.Parent.Humanoid then return end
if debounce[humanoid] == true then return end
debounce[humanoid] = true
humanoid:TakeDamage(10)
task.wait(1)
debounce[humanoid] = nil
end
Remote.OnServerEvent:Connect(function()
-- if the player is already attacking then exit this function early
if attacking == true then return end
-- set attacking to true to stop the player from attack again
attacking = true
-- start listening for touches
touchedConnection = Blade.Touched:Connect(Touched)
-- wait 1 second
task.wait(1)
-- stop listening for touches
touchedConnection:Disconnect()
-- set attacking back to false to allow the player to attack again
attacking = false
end)
I believe since BladeHit is out of the remote listener’s scope then it’s being rewritten as a different connection therefore the previous connection is lost. (define BladeHit inside the OnServerEvent listener)
Remote.OnServerEvent:Connect(function(playerWhoFired)
local BladeHit = Blade.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid ~= Tool.Parent.Humanoid then
hit.Parent.Humanoid:TakeDamage(10)
end
end)
wait(1)
BladeHit:Disconnect()
end)