just like in the title, i want to run the touched function only once but for all the character body parts, not a specific one, like the torso, so basically do something if a body part is touched only if its the first one thats getting touched
You would use a for
loop and :Once()
to achieve this.
local function touched(hit)
print(hit)
end
for _, part in ipairs(char:GetChildren()) do
if part:IsA("BasePart") then
part.Touched:Once(touched)
end
end
However, if you wanted the touched event to disconnect all touched connections, you would create a table to store the connections, and disconnect them when it is fired.
local connections = {}
local function touched(hit)
print(hit)
for _, connection in ipairs(connections) do
connection:Disconnect()
end
end
for _, part in ipairs(char:GetChildren()) do
if part:IsA("BasePart") then
table.insert(connections, part.Touched:Once(touched))
end
end
However, the parts of the character may touch each other and fire the event, which I’m guessing you don’t want, in which case you would have to do this:
local connections = {}
local function touched(hit)
if not hit:IsDescendantOf(char) then
print(hit)
for _, connection in ipairs(connections) do
connection:Disconnect()
end
end
end
for _, part in ipairs(char:GetChildren()) do
if part:IsA("BasePart") then
part.Touched:Connect(touched) -- Using :Connect() because it will disconnect even if the part touched was a character part
end
end
doesnt seem to work for me, the prints work, but i have some other lines of code that i dont know where to place, can you help me?
Put your variable declarations above all my code, as shown.
local players = game:GetService("Players")
local player = players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
-- etc
-- My code snippet here
Put the code that executes whenever the part is touched in place or after the print(hit)
.
local function touched(hit)
if not hit:IsDescendantOf(char) then
print(hit) -- Replace this with to-be-executed code
-- OR put it right here
for _, connection in ipairs(connections) do
connection:Disconnect()
end
end
end
If your to-be-executed code yields (it has a wait()
or anything like that in it) I would put the for loop that disconnects the connections above it, like this.
local function touched(hit)
if not hit:IsDescendantOf(char) then
for _, connection in ipairs(connections) do
connection:Disconnect()
end
print(hit) -- Replace this with to-be-executed code
-- OR put it right here
task.wait(1) -- If your code has something like this
char.ChildAdded:Wait() -- Or this
-- It yields, and you should do above
ened
end
If you have any other connections, I would put them below everything, at the very bottom of the script.
-- ALL the other code
player.CharacterAdded:Connect(function)
-- etc, etc
Let me know if you have any other code you don’t know where to put.
The script still seems to be running infinitely, does it have anything to do that its in a modulescript?