Sword Script Not Functioning As Intended

local sword = script.Parent
local maxdistance = 5

sword.Equipped:Connect(function()
	while true do
		local Dummy = workspace:GetChildren()
		
		for _, Dummy in pairs(Dummy) do
			if Dummy:IsA("Model") and Dummy.Name == Dummy then
				local distance = (sword.Parent.Torso.Position - Dummy.Torso.Position).Magnitude
				
				if distance < maxdistance then
					local anim = script.Animation
					anim:Play()
					
					local humanoid = Dummy:FindFirstChild("Humanoid")
					if humanoid then
						humanoid:TakeDamage(25)
					end
				end
			end
		end
	end
end)

(I have it as equipped so it does it automatically without the player clicking it)
(I also have it set to Dummy to test if it deals damage to the humanoid)

This script is supposed to find an enemy within 5 studs, and play an animation, and deal damage to that enemies humanoid

None of it works, so if anyone can help me out, that would be great!

You’re creating an infinite loop without yielding, so you’re probably getting a script execution timeout. Add a wait. Also you should use another condition for your loop as you have a memory leak, you’re creating a new thread that lasts forever every time the sword is equipped.

How would I get rid of the memory leak?

Use a different condition for your loop. What I’d do is make a variable that gets changed whenever the tool is equipped/unequipped. So something like:

local isEquipped = false

on tool equipped, isEquipped = true
while isEquipped do
    check magnitudes etc
end

on tool unequipped, isEquipped = false

I’m gonna head to sleep, but first thing I’ll try to fix that

1 Like

Instead of doing for _, Zombie in pairs(Zombie) do, try using for _, [random name] in pairs(Zombie)

Then you would change the other Zombies inside the for loop to the aforementioned [random name].

Instead of the value and table that pairs is referring to being the same, you should use a different variable; for example, most people use for i, v in pairs([table name]) do.

It’s okay here as they’re just overwriting the previous value and from what I see they don’t ever need to access the previous value of Zombie.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.