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

How to check if a part is touched?

I made this script to make a part give random weapons to players if that part is touched:

local weapons = game.ServerStorage.Weapons:GetChildren()

script.Parent.Touched:connect(function(plr)
	local weapon = weapons[math.random(#weapons)]
	
	weapon:Clone().Parent = plr.Backpack
	
	script.Parent:Destroy()
end)

It says "Touched is not a valid member of Model".

1 answer

The .Touched signal only applies to BasePart Instances. A Model is a container Object. You can use it's .PrimaryPart property to get the existing centre most, or assigned BasePart.

local serverStorage = game:GetService("ServerStorage")
local players = game:GetService("Players")

local weapons = serverStorage.Weapons:GetChildren()

local model = script.Parent
local part = model.PrimaryPart

part.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
    if (humanoid and humanoid.Health > 0) then
        local player = players:GetPlayerFromCharacter(hit.Parent)
        local backpack = player:WaitForChild("Backpack")
        local weapon = weapons[math.random(#weapons)]:Clone()
        weapon.Parent = backpack
        model:Destroy()
    end
end)

The signal doesn't supply a Player Object either, but the actual Instance of contact. You must filter for a Humanoid to ensure we're dealing with a Character Rig, then, you must uplink the Player from the Character instead.

5 comments

0

Sorry it's not a part. It's a model. I still tried this anyway but it said, backpack is not a valid member of meshpart.

0

Use the code above.

0

there's an error at line 14. output says.

0

please holp

0

Can you tell me the error?

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