Hello, I have a question about using the .touched event.
For an example, I have like 50 kill blocks in an obby game, would I be better off to use a loop and add a touch event to each kill block or would I be better off adding a touch even to each players humanoid root part when a player joins?
So, you’re wondering whether or not you should add .Touched to the kill block, or the HumanoidRootPart?
First of all, I don’t think the HumanoidRootPart would even touch the kill block most of the time. Also, the HumanoidRootPart will touch so many more parts than the kill block ever will, so the better option would be adding the .Touched event to the kill block.
Since you have so many kill blocks, I’d just have one script inside whatever folder/model contains all the kill blocks, and use :GetChildren() and a for loop. Example:
-- Script parented to the parent of the kill blocks
local players = game:GetService("Players")
local root = script.Parent
local children = root:GetChildren()
local function touched(hit)
local char = hit:FindFirstAncestorWhichIsA("Model")
if char then
local player = players:GetPlayerFromCharacter(char)
if player then
local hum = char:WaitForChild("Humanoid")
hum.Health = 0
end
end
end
for _, killBlock in ipairs(children) do
if killBlock:IsA("Part") and killBlock.Name == "Kill Block" then -- If the kill block isn't a simple part, then replace the string in the :IsA method with whatever class it is, and replace the Name string with whatever you named the kill bricks.
killBlock.Touched:Connect(touched)
end
end
Its not actually for an obby or kill blocks or anything like that, that was just an example so people get the point. The real reason is for a train system I’m working on. I have multiple blocks that will get touched for different things like level crossings, signaling, passenger information displays and maybe a few other things. Each train has a coupler block at the front and back and when the coupler touches another trains coupler it will couple and I had an idea I could also make it so if the coupler touches a level crossing activator or something.
Basically I’m wondering weather the event should be hooked onto each activator part or weather I should hook the event to the coupler. Like what is more optimized
In my opinion, I think hooking the event to the trains coupler would be better but I made this post to sort of confirm this.
It sounds like the coupler would touch the least amount of parts- assuming that the activator is big enough to touch every single part of the train. However, the activator might be more reliable, assuming it’s anchored in place. .Touched events can be fishy, especially when dealing with moving parts.
See if doing the coupler is completely reliable, all the time. If not, do the activator instead.
True and I should be spending less time hooking events to things and bonus, I already have a touched event in the coupler that will be used for coupling trains…