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.
How to make OnTouch only apply for 1 part???
2 answers
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.
function OnTouched(hit)
if hit.Parent.Name == "" then --put the parts name inside of ""
--code stuff
end
This discussion is preserved as it was. New answers, comments, and votes are closed.
