Code gets error when needs to delete a child of a parent

Hello, i have this issue where my code errors whenever it try’s to delete/Destroy a child of parents.
here is my code:

local label = script.Parent.Parent.HealthPart.Health
local treeStem = script.Parent
local swingsLeft = 10
local animation = script:WaitForChild("Dance2")
local humanoid = script.Parent.Parent:WaitForChild("Humanoid")
local dance = humanoid:LoadAnimation(animation)
local animation2 = script:WaitForChild("Fall")
local animationFall = humanoid.Animator2
local FallDance = humanoid:LoadAnimation(animation2)


local function onTouch(otherPart)
	local tool = otherPart.Parent
	if tool:IsA('Tool') and tool.Hitting.Value == true and otherPart.Parent.Name == "Axe" then
		swingsLeft -= 1
		label.GreenHealth.Size = UDim2.new(swingsLeft/10, 0, 1, 0)
		
		dance.Looped = false
		dance:Play()
		

		
	else
		if otherPart.Parent.Name == not "Axe" then
			return nil
		end
	end
	if swingsLeft <= 0 then
		if script.Parent.Parent:FindFirstChild("Leaves") then
			FallDance.Looped = false
			FallDance:Play()
			FallDance.Stopped:Wait()
			FallDance:stop()
			

			if FallDance.Ended or FallDance.Stopped then
				script.Parent.Parent.Leaves:Destroy()
				
				script.Parent.Parent.HealthPart.Health.Enabled = false
				if script.Parent.Parent.TreeStem2.ProximityPrompt.Enabled == false then

					script.Parent.Parent.TreeStem2.ProximityPrompt.Enabled = true
					script.Parent.Parent.TreeStem2.Anchored = false
					script.Parent.Parent.TreeStem:Destroy()
					script.Parent.Parent.HealthPart:Destroy() -- here comes the error what i was talking about
					script.Parent.Parent.HumanoidRootPart:Destroy()

			end

			end

			

		end
	end
end

treeStem.Touched:Connect(onTouch)

i get this error:Workspace.Tree.TreeStem.Script:45: attempt to index nil with ‘Parent’

here is a picture of my childs and parents:
image

does anybody know how to fix this?

Error comes on line: Script.Parent.Parent.HealthPart:Destroy

I think it’s because you deleted the tree stem with the script in it. Try to do that last or move the script to the tree model.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.