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

Players touching objects?

I am wondering if there is a more efficient way to detect if a player is touching a part so that it does something.

function  ontouch (hit)
If hit == game.players.localplayer.Character:findFirstChild("Torso")
       then print ("ow")
end

script.parent.touched:connect(ontouch)

1 comment

0

I added a few more detail for your benefit.

1 answer

✓ Accepted answer

Your script errors

  • Only LocalScripts can access LocalPlayer, and Local Scripts don't work in Workspace.

  • You were missing an end

In my solution, I got rid of these errors for you. I'll be using a regular script inserted into a part in workspace.


How to/Solution

I would suggest checking if the part's name is "Torso",

--Regular script
function  ontouch(hit)
	if hit.Name == "Torso"then 
		print ("ow")
	end
end

Script.Parent.Touched:connect(ontouch)
I added some fixes to your script as well.

But what if you have parts in your game named "Torso"?

I would suggest making sure that what touched the part was a Humanoid,

--Regular script
function  ontouch(hit)
	if not hit.Parent:FindFirstChild("Humanoid") then return end--Checks Humanoid
	if hit.Name == "Torso"then 
		print ("ow")
	end
end

Script.Parent.Touched:connect(ontouch)
Returns end if the part's parent doesn't have a humanoid

But what if it's not a player?

Check if it's a player,

--Regular script
function  ontouch(hit)
	if not game.Players:GetPlayerFromCharacter(hit.Parent) then return end--Checks for Player
	if hit.Name == "Torso"then 
		print ("ow")
	end
end

Script.Parent.Touched:connect(ontouch)
Returns end if the part's parent is not a character of a player

You could of course do this with arms and legs as well.


Hope I helped!

Good Luck!

If I helped you, make sure to hit that accept button!

2 comments

0

Thank you the first one really helped.

0

np

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