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

Players touching objects?

Asked by 8 years ago

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)
0
I added a few more detail for your benefit. User#11440 120 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago

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!
0
Thank you the first one really helped. Frandavi1000 15 — 8y
0
np User#11440 120 — 8y
Ad

Answer this question