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

How to detect if player touched a part?

Asked by 4 years ago

I have this script for a loot crate that will give a random weapon if touched.

math.randomseed(tick())

script.Parent.Touched:Connect(function(hit)
    script.Disabled = true

    local player = hit.Parent.Name
    local random = math.random(1,100)

    if random > 0 and random < 50 then
        local ar = game.ServerStorage.AR:Clone()
        ar.Parent = game.Players[player].Backpack

    elseif random > 50 and random < 100 then
        local crossbow = game.ServerStorage.Crossbow:Clone()
        crossbow.Parent = game.Players[player].Backpack
    end

    script.Parent:Destroy()
end)

The problem is, it didn't work. It says: "Touched is not a valid member of Part"

Please help, thank you! <3

0
You've forgot a end after line 11. SilentsReplacement 468 — 4y
0
He was using `elseif` though User#29913 36 — 4y
0
Make sure script.Parent is a part Nguyenlegiahung 1091 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

Hello. You'd need an if statement checking if the player isn't nil from the :GetPlayerFromCharacter() function. It gets that player from its character, hi.Parent. Try this:

math.randomseed(tick())

script.Parent.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)

    if player then
        script.Disabled = true

        local random = math.random(1,100)

        if random > 0 and random < 50 then
            local ar = game.ServerStorage.AR:Clone()
            ar.Parent = player.Backpack

        elseif random > 50 and random < 100 then
            local crossbow = game.ServerStorage.Crossbow:Clone()
            crossbow.Parent = player.Backpack
        end

        script.Parent:Destroy()
    end
end)

Please accept and upvote this answer if it helped.

Ad

Answer this question