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

Can someone please explain to me how to use the touched function?

So basically what im trying to do is give a player a sword on the event of touching a part. I tried running this script and it didn't work (stopped on the function part). Could someone help me understand what i did wrong and how to fix it?

local sword = game.ReplicatedStorage.ClassicSword local swordgiver = script.Parent local player = game.Players.LocalPlayer

swordgiver.Touched:Connect(function(hit) sword:Clone().Parent = player.Backpack wait(.5) print('sword has been given') end)

2 answers

I can help, My 2nd time answering.

Notes:

--[[

1. This needs to be a script, And not a localscript. Scripts are serversided.
2. Parent the script to the part.

]]

Here's the script


local sword = game.ReplicatedStorage.ClassicSword 
local swordgiver = script.Parent

swordgiver.Touched:Connect(function(hit)
	if hit:IsA("Part") or hit:IsA("MeshPart") or hit:IsA("UnionOperation") or hit:IsA("Accessory") then
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		local NewSword = sword:Clone()
		
		NewSword.Parent = plr.Backpack
	end
end)

.touched can be used on any physical thing in the workspace, for example: unionoperations, negateoperations, parts, meshparts, flagstands, seats, etc.

to use .touched, you can put it in a localscript or regular script and it will work. to use it, all you have to do is define the instance you want to use the .touched function on and use a :Connect as seen below:

local p = Instance.new("Part",workspace)
p.Touched:Connect(function(j) -- j is the instance that touched p
	print(j,j.Parent)
end)

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