✓ Accepted answer
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
local function search()
local children = workspace:GetDescendants()
local characters = {}
local humanoids = {}
for _, v in pairs(children) do
if v:IsA("Model") then
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
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
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
6 comments
If you are wanting to do something like damage per second, i'd recommend using either region 3, or magnitude. The way you have this script, it is going to slow down the game by alot. You are connecting the touched function every time it loops.
secondly, you don't need the 'for' loop, as I am guessing that your 'Part' doesn't have any children that you need to grab.
Question 1: Is your 'Part' a model, or a physical part, and does it have any children?
Um it seems your doing a hitbox type of thing. You should put a invisible brick overlapping your thing and connect the touched from there
I think you cannot put a function into a if statement, loop or while waits. It I what you Did at line 6.
the part is not a model