Search code examples
luarobloxroblox-studio

Check if a part is a part of a character | Roblox


I am not sure where to start so asking for some help. I want to create a script that detects if the part is hit by a person.

Can anyone give an idea?

local Debris = game:GetService("Debris")
local wall = script.Parent

script.Parent.Touched:Connect(function(hit)
    if hit.Name ~= "Rails" then
        if hit.Name ~= "Baseplate" then
            if hit.Name ~= "Essential" then
                local explode = Instance.new("Explosion")
                explode.Parent = hit
                explode.Position = hit.Position
                hit:BreakJoints()
                Debris:AddItem(hit, 5)
            end
        end
    end
end)

Thanks


Solution

  • We can use FindFirstAncestorOfClass and FindFirstChild together for finding whether a part is a child of the Player.Character.

    If hit has a Model ancestor and that ancestor has a Humanoid, we can assume that Model is the Player.Character.

    In the below script, I made it so that whenever script.Parent is touched we check for a Model ancestor and then if that Model has a Humanoid. If so we add an explosion to it.

    local Debris = game:GetService("Debris")
    local wall = script.Parent
    
    script.Parent.Touched:Connect(function(hit)
        local characterModel = hit:FindFirstAncestorOfClass("Model")
        if characterModel then
            local humanoid = characterModel:FindFirstChild("Humanoid")
            if humanoid then
                local explode = Instance.new("Explosion")
                explode.Parent = hit
                explode.Position = hit.Position
                hit:BreakJoints()
                Debris:AddItem(hit, 5)
            end
        end
    end)
    

    Note that you may need to modify the code for explode. It is unclear in your question what to do if we hit the Player so I left it as is.

    You can use hit for the Player's Part we hit, humanoid for the Player's Humanoid and characterModel for the the Player's Character.