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

Why does my OnTouch script get this error "attempt to index field 'Parent'" ?

16:31:49.116 - Workspace.GameFiles.RedFile.WalkPoints.Gem.Head.ObjectiveTest:2: attempt to index field 'Parent' (a nil value)

function onTouched(hit)
if hit.Parent.Name == "RedUnit" then 
	script.Parent.Parent.Humanoid.Health = script.Parent.Parent.Humanoid.Health - 20
	hit.Parent:Destroy()
end
end

connection = script.Parent.Touched:Connect(onTouched)

6 comments

0

Does 'hit.Name' work instead of 'hit.Parent.Name'?

0

i tried that and it didnt sadly.

0

I forgot to mention the script actually works perfectly but this error comes up, its rather weird.

0

It just happens because sometimes the hit object is from something other than "RedUnit" and apparently doesn't have Parent of it's Parent. If this bothers you just make a check to determine if hit.Parent has a humanoid before changing it's health.

0

The only thing hitting it is body parts of a naked npc, so i dont think thats the problem

0

I had that problem a while ago, strangely it stopped after a while. Could it be the newest ROBLOX update?

1 answer

Try

function onTouched(hit) if hit.Name == "RedUnit" or hit.Parent.Name == "RedUnit" then script.Parent.Parent.Humanoid.Health = script.Parent.Parent.Humanoid.Health - 20 hit.Parent:Destroy() end end

connection = script.Parent.Touched:Connect(onTouched)

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