Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why do I keep getting this error?

I have a script inside a part, and when you touch the part, you're supposed to die, but when it touches the grass, it removes itself, and when it touches a part, it sets anchored to false. But when it touches you, a error comes up

21:33:27.795 - Workspace.GameRock.RockS:2: attempt to index field 'Parent' (a nil value)

Script:

script.Parent.Touched:connect(function(part)
	local h = part.Parent:findFirstChild("Humanoid")
	local g = part.Parent:findFirstChild("Grass")
	local p = part.Parent:findFirstChild("Part")
	local r = part.Parent:findFirstChild("Rock")
	if h then
		h.Health = 0
	elseif g or r then
		script.Parent:Destroy()
	elseif p then
		p.Anchored = false
	end
end)

EDIT:

Sometimes the error happens, and other times it doesn't happen. but more often than not.

1 comment

1

Usually, when I think of this type of Error, I think of the code 'if not hit.Parent then return end' to prevent something like this from happening, although, I don't suggest doing this, just a thought. :)

2 answers

✓ Accepted answer

Actually Alpha, you should always do something like that. Otherwise if a part touches it, then is removed at that second, it'll bug out.

SuperCoolGuy53, here is the revised code using Alpha's suggestion:

script.Parent.Touched:connect(function(part)
    if not part then
        return end
    else
        if not part.Parent then
            return end
        else
            local h = part.Parent:findFirstChild("Humanoid")
            local g = part.Parent:findFirstChild("Grass")
            local p = part.Parent:findFirstChild("Part")
            local r = part.Parent:findFirstChild("Rock")
            if h then
                h.Health = 0
            elseif g or r then
                script.Parent:Destroy()
            elseif p then
                p.Anchored = false
            end
        end
    end
end)

1 comment

0

I'll try it.

Shouldn't your conditional statement be right after, "local h =", and before part.Parent:findFirstChild("Humanoid")?

1 comment

0

That won't do any change; It'll only reverse it's Positions, doing the same task.

This discussion is preserved as it was. New answers, comments, and votes are closed.