I made a script, it is supposed to check and see if the player's torso is on fire! It removes it if the torso is on fire, but if there is no fire it breaks, and sends errors. I understand it can't check for something if it doesn't exist, but I know you can do it somehow! Here is my script
function onTouched(hit) if hit.Parent.Torso.Fire then hit.Parent.Torso.Fire:remove() end end script.Parent.Touched:connect(onTouched)
Output: 10:37:21.224 - Fire is not a valid member of Part Please help!!! Thank you!!!
function onTouched(hit) if hit.Parent.Torso:findFirstChild("Fire") then -- it will return nil if it's not found, replace it with this. hit.Parent.Torso.Fire:remove() end end script.Parent.Touched:connect(onTouched)
function onTouched(hit) if hit.Parent.Torso:FindFirstChild("Fire") then hit.Parent.Torso.Fire:remove() end end script.Parent.Touched:connect(onTouched)
Indexing game objects directly will error if they do not exist.
You're trying to check if it exists, but your already assuming it exists! You write a reference to hit.Parent.Torso.Fire
, trying to check if it exists, but the very existence of the reference means that you're already assuming it exists. If it doesn't, then you get the error.
You need to use FindFirstChild
. This method will look for the child, and, if it finds it, return that child. If it doesn't find it, then it returns nil. But because it works like a function, this won't result in an error.
if hit.Parent.Torso:FindFirstChild("Fire") then hit.Parent.Torso.Fire:remove() end
But wait a second. How do we know if the torso exists? Sure, it will if you touch the part, but it certainly won't if some other brick touches the part. Let's add this to our check:
if hit.Parent:FindFirstChild("Torso") and hit.Parent.Torso:FindFirstChild("Fire") then hit.Parent.Torso.Fire:remove() end