Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 9 years ago

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

Log in to vote
2
Answered by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
9 years ago

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)
Ad
Log in to vote
4
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

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) 
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 BinaryResolved 215 — 9y

Answer this question