Help with errors from nil / ignoring it

Hi community

in my game, i create new instances in the zombies to tag the player killing it. I have a function to award the score when the zombie dies. However, sometimes the zombie may die from the environment. I have a check for this :

if Zombie.KillingPlayer ~= nil then
award to KillngPlayer

However i am getting errors of KillingPlayer is not a valid member of Model. Shouldn’t my ~= nil catch such scenarios? This also breaks the script leaving corpses in the game lol.

Hence i then tried to make a catch all to remove corpses so i did

local descendants = workspace:GetDescendants()
for index, descendant in pairs(descendants) do
if descendant.Name == “Humanoid” and descendant.Health == 0 then
descendant.Parent:Remove()
end
end

but it seems that the code sometimes catch functioning dead zombies in the progress of removing from workspace as this error appeared : attempt to index nil with ‘Remove’ this also breaks the script

Am at a lost. As a learning, is there a way to ignore this error?

1 Like

Go to your explorer, screenshot your zombie instance. (Included all part).

1 Like

Zombie.KillingPlayer ~= nil
This would be an appropriate check if KillingPlayer was the property of an instance. If you are checking for an instance itself, use the dedicated method instead: Zombie:FindFirstChild("KillingPlayer") ~= nil

2 Likes

Ok thank you :slight_smile:

Btw is there anyway to ignore such errors? Just for my learning. Thanks.

To ignore errors you could call that in a pcall.

pcall(function()
    if zombie:FindFirstChild("KillingPlayer") ~= nil then
        -- Perform action
    end
end)
4 Likes

Thanks. . in this scenario, will the while loop continue?

pcall(function()
while Humanoid.Health > 0 do
if zombie:FindFirstChild(“KillingPlayer”) ~= nil then
– ERROR happens here
end
end
end

The pcall() should be inside the while loop if you want the loop to keep going when theres an error.

1 Like

Ok.

thanks @KhaosDev .

as my game is very fast paced with deaths etc all happening… the chance of a mid point break is high. Hence it seems like my scripts will be full of pcalls. From a proper scripting / performance etc point of view, no issues with such right?

As long as theres a wait() inside your while loop it should be fine.

1 Like