The part is cloned from replicated storage from a another script after a tool is activated.
This script won't harm anyone: Feel free to ask questions!!!!
local part = game.Workspace:FindFirstChild("Part") while true do wait(0.1) if part ~= nil then for i, v in pairs(part)do v.Touched:Connect(function(hit) local enemyHumanoid = hit.Parent:FindFirstChild("Humanoid") local alreadyHit = Instance.new("BoolValue") alreadyHit.Parent = hit.Parent alreadyHit.Name = "AlreadyHit" enemyHumanoid:TakeDamage(50) spawn(function() wait(1) alreadyHit:Destroy() end) end) end end end
Thanks for the Help!
I'd recommend using either region3 or raycasting, but Magnitude works alright.
With what you have done, you are connecting the touched function to the part with every loop. This isn't a good thing.
Secondly, you were using a for pairs loop for a singular part. This won't work because it isn't a table.
local part = game.Workspace:FindFirstChild("Part") local maxdist = 7 --max distance from the part local function search() local children = workspace:GetDescendants() local characters = {} local humanoids = {} ---------------------------------------------------------------- for _, v in pairs(children) do if v:IsA("Model") then --grabs models only if v:FindFirstChildOfClass("Humanoid") then if v:FindFirstChildOfClass("Humanoid").Health >0 then table.insert(characters, #characters + 1, v) end end end end ---------------------------------------------------------------- for _, v in pairs(characters) do --checking the distance between parts local primarypart = v.PrimaryPart if primarypart then local distance = (primarypart.Position - part.Position).Magnitude if distance <= tonumber(maxdist) then table.insert(humanoids, #humanoids + 1, v) end end end ---------------------------------------------------------------- for _, humanoid in pairs(humanoids) do --damaging the humanoids local human = humanoid:FindFirstChildOfClass("Humanoid") if human then if human.Health >0 then human:TakeDamage(50) end end end ---------------------------------------------------------------- children = nil characters = nil humanoids = nil end while part ~= nil do wait(0.5) search() end
Maybe test this script out. If it isn't to your liking, then I'd suggest looking up both region3, and raycasting.
https://developer.roblox.com/en-us/articles/Making-a-ray-casting-laser-gun-in-Roblox https://developer.roblox.com/en-us/api-reference/datatype/Region3