local Tool = script.Parent
local Handle = Tool.Handle
Handle.Touched:Connect(function(OtherPart)
local EnemyHumanoid = OtherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if EnemyHumanoid then
Tool.Activated:Wait() -- Checks if the tool was clicked before damaging Humanoid
EnemyHumanoid:TakeDamage(100)
end
end)
One of the main issues of this script is that it causes a memory leak. Let’s say you hit a whole bunch of enemies, but you never activated the tool. Not only would these references to all the enemies stay, but when you do activate the tool, all the enemies you touched prior to activation will all be killed.
I would recommend removing Tool.Activated:Wait(). Add a variable, name it anything (I’d recommend Active as a name). Connect Tool.Activated to this:
Tool.Activated:Connect(function()
Active = true
task.wait(.5)
Active = false
end)
In the touched function, you’d return if Active is false. At the top of the connection, put if not Active then return end. You should be good now.
Thanks for the help it has definitely improved things.
This is what I have now:
local Players = game:GetService("Players")
local Tool = script.Parent
local Handle = Tool.Handle
local Debounce = false
Handle.Touched:Connect(function(OtherPart)
local EnemyHumanoid = OtherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if EnemyHumanoid and EnemyHumanoid.Health > 0 and not Debounce then
Debounce = true
EnemyHumanoid:TakeDamage(100)
Players:GetPlayerFromCharacter(Tool.Parent).leaderstats.XP.Value += 15
task.wait(0.5)
Debounce = false
end
end)
This script changes the meaning of your old one by using a debounce. If the tool does not need to be activated to use it, this is a good design, except for the fact that Players:GetPlayerFromCharacter(Tool.Parent) could be assigned to a variable once the tool is equipped the first time, but it will not cause a memory leak.