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

Script doesn't check if "Fire" exists?

Asked by 9 years ago

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!!!

3 answers

Log in to vote
3
Answered by 9 years ago
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)

Ad
Log in to vote
2
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
9 years ago
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.

Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

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

Answer this question