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

Is there a way to detect when a player touches a part.. (Continued in question)?

Is there a way to detect when a player touches a part when can-collide is set to true and transparency is set to 1. I am using the following script to destroy "Hats" when the player touches it. But it doesn't work when the above conditions are

function onTouched(hit) 
	local d = hit.Parent:GetChildren() 
	for i=1, #d do 
		if (d[i].className == "Hat") then 
			d[i]:remove() 
		end 
	end
end 
script.Parent.Touched:connect(onTouched) 

2 answers

✓ Accepted answer

Well, everything that touches the brick may not always be a Player, so you need to check. Also, remove is deprecated, so you need to use Destroy()

script.Parent.Touched:connect(function(hit)
	if hit.Parent and game.Players:GetPlayerFromCharacter(hit.Parent) then
		for i,v in pairs(hit.Parent:GetChildren()) do
			if v:IsA('Hat') then
				v:Destroy()
			end
		end
	end
end)

Your Problem

When you index 'className' on line 4. you're probably getting an error like Attempt to index a nil value. This happens because the property you're trying to index is case sensitive, meaning you must get all the capitalization exactly right. The proper way to say it is ClassName.


Efficiency Fixes

Instead of indexing the ClassName Property, use the IsA function.

Check if there's a Humanoid in hit.Parent, that way you know it's a player that hit the object, and the event isn't firing when a part or something hits the object.

Use a generic for loop with the pairs function, as it's meant to iterate through tables.

Use the Destroy function!! Remove is deprecated


Your Code

function onTouched(hit) 
	local d = hit.Parent:GetChildren() 
	for i = 1, #d do 
		--'ClassName' is case sensitive(:
		if d[i].ClassName == "Hat" then 
			d[i]:Destroy()
		end 
	end
end 

script.Parent.Touched:connect(onTouched) 

Efficiency Edited Code

function onTouched(hit) 
	--Check for a humanoid
	if hit.Parent:FindFirstChild('Humanoid') then
		--Use generic for, with pairs function
		for i.v in pairs(hit.Parent:GetChildren()) do
			--Use the 'IsA' function
			if v:IsA('Hat') then
				v:Destroy()
			end
		end
	end
end

script.Parent.Touched:connect(onTouched) 

1 comment

0

Thanks for the answer, but Shawnyg has less rep so.. I am going to accept his answer. But i appreciate both of yours :D

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