Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does this script keep giving an error of removing a zombie when it dies in my game?

Asked by 5 years ago

This is the error and my code.

Workspace.Zombie.Remove:3: attempt to index field 'Parent' (a nil value) 21:22:39.251 - Stack Begin

while true do
    wait(0.1)
    if script.Parent.Zombie.Health == 0 then
        script.Parent:Destroy()
    end
end
0
Use the Died event instead User#19524 175 — 5y

2 answers

Log in to vote
0
Answered by
yHasteeD 1819 Moderation Voter
5 years ago
Edited 5 years ago

You need to detect if the item is valid for this use FindFirstChild After deleting use break to stop script. You can use this script:

while true do
    wait(0.1)
    if script.Parent:FindFirstChild("Zombie") then
        if script.Parent.Zombie.Health == 0 then
            script.Parent:Destroy()
            script:Destroy()
            break
        end
    end
end
0
Thanks, it worked! protectiverobos -50 — 5y
0
note: :FindFirstChild() ~= nil is redundant and unneeded - you can simply type if :FindFirstChild() then. ;p SummerEquinox 643 — 5y
0
if FindFirstChild() then will check to see if the parameter is truthy. If what FindFirstChild is searching for is nonexistent it will return nil - which is not truthy, and will not proceed with the statement. SummerEquinox 643 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

Consider the following code:

local a = (0)

while (true) do
    a = (a + 1)
    wait()

    if (a == 15) then
        script:Destroy()
    end

    print(a)
end

On every wait(), a will increase by a value of 1, until reaching 15 - upon which, the script will be destroyed... however; this occurring does NOT end our loop - because we never broke the loop. So... the actual output of the above code would be (1,2,3,4,5 --> inf). It would never end.

Now, apply the same concept to the code you have provided. Whenever the script detects that the zombie has no health remaining - it destroys the script's parent, effectively destroying the script as well. Our loop will continue to run once this script is destroyed... SO, we are still checking the if statement every 0.1 seconds. You are getting an error because script.Parent is nil now that you have destroyed the script's parent.

To fix this, break your loop when you destroy the script.

while true do
    wait(0.1)
    if script.Parent.Zombie.Health == 0 then
            script.Parent:Destroy()
        break
    end
end
0
Thanks, but yHasteeD's works well, and he answered first. protectiverobos -50 — 5y
0
Fair enough - at the very least hopefully my explanation will allow you to better understand where the error is coming from. :) SummerEquinox 643 — 5y

Answer this question