Delay in a script

Hello, what happens is that I have a script in a block that makes that if you touch it it kills you, but the problem is that when you touch it it takes up to 2 seconds to die, and I don’t know what it might be, here is the script to see if you find any errors. Thanks (I’m new to Roblox Forum)

function onTouched(part)
 local h = part.Parent:findFirstChild("Humanoid")
 if h~=nil then
  h.Health = h.Health-100
 end
end
script.Parent.Touched:connect(onTouched)
2 Likes

Try replacing the h.Health = h.Health-100 to h.Health = 0

2 Likes

Just replace that with this:

script.Parent.Touched:Connect(function(h)
    if h.Parent:FindFirstChild('Humanoid') then
        h.Parent:WaitForChild('Humanoid').Health = 0
    end
end)

When using touched events, the best way to get a player is players:GetPlayerFromCharacter(hit.Parent) otherwise an npc could trigger it.

These next things makes no performance different but it just makes the code look cleaner, instead of

foo = foo - 1 you can just do foo -= 1. And for checking values, there’s no need to do

If foo ~= nil or foo == false, you can just do if not foo

And for true or checking if it exists just

if foo then

Yes, but is there a way that I can only reduce your health by 100? Since some players have 200 lives with GamePass and the idea of ​​GamePass is that you don’t die with a single touch (Sorry if you don’t understand me, I speak Spanish and I don’t know how to write in English)

script.Parent.Touched:Connect(function(h)
    if h.Parent:FindFirstChild('Humanoid') then
        h.Parent:WaitForChild('Humanoid').Health -= 100
    end
end)

The common issue comes from the form of replication lag. Your character on the server is actually behind and it is interpolating your position based on your input. This is because of the common practice of client-server model.

1 Like