Introduction
Hello there, in this tutorial you will learn how to optimize your touched events which utilize the player’s character. Such as killbricks. To make them more responsive/reactive and reduce delay. This tutorial can also be applied to other detection methods (eg hitboxes/gun systems) that utilize spatial queries such as raycasting, getpartsboundsinbox etc.
Tutorial
Let’s take killbricks as an example. Many scripters, with years of experience. Handle killbricks like this.
Part.Touched:Connect(function(Hit)
local Character = Hit.Parent
local Humanoid = Character:FindFirstChild("Humanoid")
if Humanoid then
Humanoid.Health = 0
end
end)
What is the problem here? Well, findfirstchild. You see, findfirstchild is 20% slower than the dot operator and almost takes almost 8 times longer than simply storing a reference to an object.
This means that the killbrick’s effects will be delayed. Making your killbrick feel less reactive. However, there is a very simple fix that will allow you to get rid of this small delay aswell.
Solution
In this example of the killbrick. We can verify if the basepart is a child of a player character through the use of the :GetPlayerFromCharacter method that is available from the Players service.
Part.Touched:Connect(function(Hit)
local Character = Hit.Parent
local IsPlayer = Players:GetPlayerFromCharacter(Character)
if IsPlayer then
Character.Humanoid.Health = 0
end
end)
Now, our killbrick’s effects will be more responsive! In the example of a killbrick and in other similiar scenarios utilizing touched events, the delay is quite minimal and not very problematic because well it’s just a killbrick (although the solution is so easy to implement you might aswell do it). But depending on your system and the state of the client/server the delay could actually mean alot more. Here’s another example.
Let’s say you have a gun system/hitbox that utilizes raycasting or other spatial query methods for hit detection. You use findfirstchild to check if the detected basepart is part of a player’s character and contains a humanoid. The delay is much more problematic here where you’d want the hit detections to have very few delays obviously since a hitbox/gun system is much more important than a simple killbrick.
The fix again would be to use other methods to verify a player character other than findfirstchild. Such as :GetPlayerFromCharacter.
Also, in a live game your server/client may be slower for whatever reason. And findfirstchild utilized in these systems only enhances the problem.
This is not to bash on findfirstchild or say that you should avoid using it. It definitely has its uses. But many scripters even with years of experience are applying it in the wrong way. The most common incorrect application of findfirstchild is with killbricks.