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

How to make OnTouch only apply for 1 part???

Asked by 8 years ago

I know how to do the ontouch function thing but I dont know how to make the function only run when a certain brick touches it.

2 answers

Log in to vote
0
Answered by 8 years ago

The function you return to the Touched event has a single argument: the base part that touched it. This argument returns the entire class of the object, meaning you can do anything with it.

One thing we could do is check the "Name" property of the object, and see if it matches a condition we give it. Like this:

-- Assuming this script is inside a part
local NameRequired = "TestPart"
local Part = script.Parent

Part.Touched:connect(function(HitPart)
    if (HitPart.Name == NameRequired) then
        print("This specific part touched me")
    end
end)

Another method that I prefer (whenever possible) is actually comparing the 2 data types themselves together. Let's say you had 2 parts named "TestPart", and you didn't want to change the name of one just to make the touched event fire on one specific part. We could do this:

-- Assuming this script is inside a part
local PartRequired = Instance.new("Part",workspace)
local Part = script.Parent

Part.Touched:connect(function(HitPart)
    if (HitPart == PartRequired) then
        print("This specific part touched me")
    end
end)

Notice how I created the part within the script in the second example. That's because I need a reference to the actual part itself, instead of just it's properties. You don't always have to create the instance inside the script when doing something like this, you could easily replace that second line of code with:

local PartRequired = workspace:FindFirstChild("TestPart")

and carry on from there. However I do recommend using this method whenever possible, to avoid potential problems and restrictions with what you can name your parts.

Ad
Log in to vote
-1
Answered by 8 years ago
function OnTouched(hit)
    if hit.Parent.Name == "" then --put the parts name inside of ""
        --code stuff
end

Answer this question