onTouched lagging game

This error only pops up when it is touching another zombie (this is a zombie damage script). I am lost at how I can check if it’s touching a player without it erroring.

Without the debounce, the lag is INSANE. With the debounce the lag is lessened but still occurs as frequently(when the zombies are grouped up touching each other.)

How do I make them unable to touch each other, but only the player? If that makes any sense.

ERROR: attempt to index local 'player' (a nil value)

local touched = false

function onTouched(hit)
		local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
        local human = hit.Parent:findFirstChild("Humanoid")
        if (human ~= nil) and player:WaitForChild('Class').Value == 'Human' and touched == false then
			human.Health = human.Health - 5
			touched = true
			wait(2)
			touched = false
        end
end
script.Parent.Touched:Connect(onTouched)

NOTE: I know it is a nil value because the zombies are not 'players'; how do I approach that error?

You are assuming that whatever the zombie has touched could be a player, instead, you should check if the player exists first. This is how I would do it:

local touched = false

function onTouched(hit)
    if touched then return end
    local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
    if player then
        local human = player.Character.Humanoid
        if human ~= nil and player:WaitForChild('Class').Value == 'Human' then
            human.Health = human.Health - 5
            touched = true
            wait(2)
            touched = false
        end
    end
end
script.Parent.Touched:Connect(onTouched)
1 Like

Thanks, I appreciate it!
I must ask, why does checking the player before touching it not give me an error? It doesn’t really make sense. Like, what is the purpose of
if touched then return end and what does it have to do with: if player then

The zombie could of touched a part which is not from a player’s character, and you did not check for this. For example, if the zombie touched a part from a building in your game, you would have attempted to get the player from that part’s parent and this would return nil as it is not a player’s character. Therefore, the if player is essentially checking if player ~= nil to make sure that you were actually able to get a player from the part’s parent.

The if touched return end is a simple way to cancel the function if touched == true.

1 Like