How to loop through every npc in a folder and assign a hitbox to them?

I am trying to make a stealth game and for the detection purpose I am using a hitbox, which I clone onto the heads of every enemy/npc. I put them all in a folder, but I am wondering how I can assign each one of them a hitbox.

6 Likes

I think you should use In Pairs inside a For loop.

5 Likes

Oh, thank you. How would I keep each of the NPCs that I get in the folder separated from each other though? And how could I individually assign them a hitbox.

4 Likes

You could normally separate them. Is this hitbox a part?

2 Likes

Yes it is a part. text limit AUUGGGGH help i mdying

2 Likes

In this case you should probably do something like this:

local folder = game.Workspace. -- insert your folder name here

for i,v in pairs(folder:GetChildren()) do -- for loop which gets children of that folder(npcs)
      local hitbox = instance.new("Part") -- this is your hitbox part
      part.Parent = v:FindFirstChild("Head")_ -- assign the parent of your hitbox
      part.Size = Vector3.new() -- here set the size of your part
      part.Name = "Hitbox" -- set the name to what you want
      task.wait() -- you can set the wait time if you want
end
1 Like

It can contain some errors. If that happens let me know!

2 Likes

Thanks man, I’ll try that out in a second.

3 Likes

You’re welcome! AHHHHHHHLIMITT

1 Like

Yo, I tried your code and did some changes. The hitbox is kept as a child of the script so instead of creating a new instance I tried to clone it, but rather then cloning it it just takes the original part and welds it to the NPC.

local folder = game.Workspace.Enemy -- insert your folder name here

for i,v in pairs(folder:GetChildren()) do -- for loop which gets children of that folder(npcs)
	local hitbox = script:WaitForChild("Hitbox")
	local hitboxClone = hitbox:Clone()
	local char = v
	
	hitbox.Parent = v:FindFirstChild("Head")-- assign the parent of your hitbox
	
	local weld = Instance.new("Motor6D")
	weld.Parent = hitbox.Parent
	weld.Part0 = hitbox.Parent
	weld.Part1 = hitboxClone
	-- here set the size of your part
	
	task.wait() -- you can set the wait time if you want
end
2 Likes

Nevermind I’m stupid I forgot to change the names around, sorry.

2 Likes

Alright, fine. Also, If you want to optimalize your game, I would suggest, better is to create a part instead of cloning it and making variables out of loops, except these e.g. “clones”, or that weld variable.

1 Like

Okay, thanks for the tips. JAiogfhawoigqjawoegjaga

1 Like

You’re welcome! dfsfesdfesdfesdfesdf

1 Like

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