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

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

Asked by
PastDays 108
5 years ago

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)
0
Does 'hit.Name' work instead of 'hit.Parent.Name'? Nikkasfied 43 — 5y
0
i tried that and it didnt sadly. PastDays 108 — 5y
0
I forgot to mention the script actually works perfectly but this error comes up, its rather weird. PastDays 108 — 5y
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. climethestair 1663 — 5y
View all comments (2 more)
0
The only thing hitting it is body parts of a naked npc, so i dont think thats the problem PastDays 108 — 5y
0
I had that problem a while ago, strangely it stopped after a while. Could it be the newest ROBLOX update? OBenjOne 190 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

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)

Ad

Answer this question