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
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
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
Thanks, it worked!
note: :FindFirstChild() ~= nil is redundant and unneeded - you can simply type if :FindFirstChild() then. ;p
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.
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
Thanks, but yHasteeD's works well, and he answered first.
Fair enough - at the very least hopefully my explanation will allow you to better understand where the error is coming from. :)
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
Use the Died event instead