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

How to use touched event??

Asked by 10 years ago

I used script.parent.Touched:connect(onTouch) but doesnt work in script when i run it

0
You forgot to capitalize the 'P' in 'Parent'. TheeDeathCaster 2368 — 10y

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

To access the Touched event we do the same thing as if it was a child or property.

Part.Touched
--With the correct path to the part; Could be Workspace.Part, or script.Parent if the script is inside the part.

Now, obviously this code by itself will do nothing.

To execute code when an event is fired we use the connect() method. This is because we need to connect a function to the event, so the function is called each time the event fires.

--Create the function
function onTouch(hit)
    print("I was touched!")
end
script.Parent.Touched:connect(onTouch)

This is fully functioning code. We have a function that we named 'onTouch' and then connected that function to the Touched event of that brick. One thing I would like to clear up is that the function can be named anything you want. The words 'onTouch' are in no way special! The following code will work exactly the same as before;

function asdfqwer(bububububu)
    print("I was touched!")
end
script.Parent.Touched:connect(asdfqwer)

Touched events also have a built in parameter, commonly named hit or part, that is equal to the part that hit the brick with the touch event. If you character steps on the brick, this parameter might be equal to your Left Leg.

This is very useful for determining if an actual character model touched the brick because we can check if the parent of the hit part has a Humanoid.

function onTouch(hit)
    if hit.Parent:FindFirstChild("Humanoid") then
        print("It's a real character")
    end
end
script.Parent.Touched:connect(onTouch)
Ad
Log in to vote
-1
Answered by 10 years ago

Can you write in your full script so we can see the problem with your script?

0
wow. nice job -1'ing me, how are we going to correct the script if you don't even show your script? ugh. detaching 8 — 10y
0
also, do you have a function named function onTouched()? cause that might be the problem, also place the script under the part. detaching 8 — 10y

Answer this question