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)
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)
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.
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
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)
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)