First post in #bug-reports. Looking for ways to improve and simplify this script I made for my Stun Baton tool. It looks unnecessarily long in my opinion and I feel like there are ways of shortening and improving it.
The stun baton damages and stuns/freezes players for a while. It’s default use cooldown time is 2.75 seconds. I had made it so if you hit a player then you’ll instead have to wait 25 seconds before using it again. The cooldown resets back after the 25 seconds are finished.
local tool = script.Parent
local handle = tool.Handle
local particles = tool.End:FindFirstChild("electricityParticles")
local touchingTool = tool.Handle:GetTouchingParts()
local isActive = false
local isTouched = false
local debounce = false
local touchdebounce = false
local cooldownTime = tool.cooldownTime.Value
local particlesTime = tool.particlesTime.Value
local anim = Instance.new("Animation")
anim.Parent = tool
anim.AnimationId = "rbxassetid://6857805039"
local function stunPlayer(target)
if target.Parent:IsA("Model") then
local targetChar = target.Parent
for i, v in pairs(targetChar:GetChildren()) do
if v:IsA("Part") then
v.Anchored = true
end
end
end
end
local function unstunPlayer(target)
if target.Parent:IsA("Model") then
local targetChar = target.Parent
for i, v in pairs(targetChar:GetChildren()) do
if v:IsA("Part") then
v.Anchored = false
end
end
end
end
tool.Handle.Touched:Connect(function(hit)
if isActive == true then
if touchdebounce == true then return end
touchdebounce = true
if hit then
local humanHit = hit.Parent:FindFirstChild("Humanoid")
if humanHit then
if humanHit.Parent == tool then return end
if humanHit.Health > 0 then
isTouched = true
cooldownTime = 25
particlesTime = 15
humanHit:TakeDamage(40)
stunPlayer(hit)
wait(17.5)
unstunPlayer(hit)
else
isTouched = false
cooldownTime = 2.75
particlesTime = 1.5
end
else
isTouched = false
cooldownTime = 2.75
particlesTime = 1.5
end
else end
wait(2)
touchdebounce = false
end
end)
tool.Activated:Connect(function()
local character = tool.Parent
local human = character.Humanoid
if debounce == true then return end
debounce = true
isActive = true
local animTrack = human:LoadAnimation(anim)
animTrack:Play()
animTrack.KeyframeReached:Connect(function(keyframeName)
if keyframeName == "startElectricity" then
if particles then
particles.Enabled = true
end
end
end)
animTrack.Stopped:Connect(function()
if isTouched == false then
cooldownTime = 2.75
particlesTime = 1.5
wait(particlesTime)
if particles then
particles.Enabled = false
end
elseif isTouched == true then
isTouched = false
end
end)
wait(cooldownTime)
debounce = false
isActive = false
end)