Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why isn't my part detection / kill script working, no output errors, how do I fix??

I made a script that is inside a model. There is also a folder called KillParts. The script is supposed to detect if you touch a kill part, but it isn't working. My script is:

local function DealDamage(part)
	local hum = part.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end

for k,n in pairs(script.Parent.KillParts:GetChildren()) do
	if n.Name == "KillPart" then
		print("Touched")
		n.Touched:Connect(DealDamage())
	end
end

It also doesn't print "Touched"

2 answers

✓ Accepted answer

I fixed this by making all of the kill parts into a union, then put my script as

function onTouched(part)
	local h = part.Parent:findFirstChild("Humanoid")
	if h~=nil then
		h.Health = 0
	end
end

script.Parent.KillPart.Touched:connect(onTouched)

Use CollectionService for handling events or other things with multiple parts.

Collection Service

CollectionService is best used with in pairs/for loops, more can be found on for loops here.

I have more of the code explained inside of the code block.

local collectionservice = game:GetService("CollectionService")

for _,v in next, script.Parent:GetDescendants() do
	if v:IsA("Part") then
		collectionservice:AddTag(v,"killpart") -- all we are doing is simply adding a tag to anything in the model that is a "Part"
	end
end
local damagetodeal = 20 -- damage we will deal to the player
local function kill(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		hit.Parent:FindFirstChild("Humanoid"):TakeDamage(damagetodeal)
	end
end

for _,v in next, collectionservice:GetTagged("killpart") do -- here we are gonna get each tagged part with a tag of "killpart" and put a touched event on it
	v.Touched:Connect(kill)
end

3 comments

0

doesn't work.

0

have you put the parts in a model and the script in the same model? because thats what i did and it worked well.

0

I fixed it. Look at the answer above to see how.

This discussion is preserved as it was. New answers, comments, and votes are closed.