Is there anyway i can make my punching system more efficient?

so. i made a simple punching animation, that plays whenever the player presses f, and does damage to an npc. im looking to find out if there is anyway i can make my script more efficient and easy to remember. below you will find the script

CanDoDmg = true -- If the player can do damage
Keybind = "f" -- Keybind to activate the punch
dmg = 10 -- How much damage the player takes


local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.KeyDown:Connect(function(key)
 if key == Keybind then
  local anim = script.Parent.Humanoid:LoadAnimation(script.Animation)
  anim:Play()
  script.Parent.RightHand.Touched:connect(function(hit)
   if hit.Parent.Humanoid and CanDoDmg == true then
   hit.Parent.Humanoid:TakeDamage(dmg)
   CanDoDmg = false
   wait(1)
   CanDoDmg = true
   end
  end)
 end
end)

My recommendations to help improve your script is this

  • Include of KeyDown, use UserInputService, as the latter is the modern and recommended to use over the legacy KeyDown. It also allows you to prevent you from punching if you’re chatting.
  • There’s no debounce for the punching bind, so you have to make a debounce for that as well
  • Nothing disconnects the Touch event, so you will still be able to damage someone even if you are not punching, so make a variable to store the connection and disconnect it after a second
  • Load the punching animation first thing before the event so yo don’t load it many times, also Humanoid:LoadAnimation() is deprecated, so you should use Humanoid.Animator:LoadAnimation()

Overall, I think this would be a better approach to it

local uis = game:GetService("UserInputService")
local bind = Enum.KeyCode.F

local char = script.Parent

local canDamage = true
local bindDebounce = false
local baseDamage = 10

local punchAnim = char.Humanoid.Animator:LoadAnimation(script.Animation)

local connection

uis.InputBegan:Connect(function(input,gpe)
	if gpe or bindDebounce then return end
	if input.KeyCode == bind then
		bindDebounce = true
		punchAnim:Play()
		connection = char.RightHand.Touched:Connect(function(hit)
			local hum = hit.Parent:FindFirstChild("Humanoid")
			if hum and canDamage then
				hum:TakeDamage(baseDamage)
				canDamage = false
			end
		end)
		wait(1)
		connection:Disconnect()
		bindDebounce = false
		canDamage = true
	end
end)
4 Likes