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

Why does my weapon inconsistently do damage? "attempt to index nil with 'TakeDamage'

I have a script under my tool, along with a bool value to correspond to help the blade only do damage when the tool is activated. Problem is that it will do damage and sometimes it won't and I can't find out why.

Problem here: https://gyazo.com/b326864ddd8a327f81d789d38e523534

Error code "13:57:57.606 - Players.Storche.Backpack.Scythe.Script:22: attempt to index nil with 'TakeDamage'" or "Humanoid is not a valid member of workspace."

local CD = true
--local color = false
script.Parent.DMG.Value = false

script.Parent.Activated:Connect(function()
	if CD == true then
		--if color == false then
			--color = true
		script.Parent.DMG.Value = true 
		--script.Parent.Damage.Transparency = 0.75
		CD = false
		wait (1)
		--script.Parent.Damage.Transparency = 1
			CD = true
			--color = false
		--end
	end
end)
	script.parent.Damage.Touched:Connect(function(p)
	if script.Parent.DMG.Value == true then
		script.Parent.DMG.Value = false
		p.Parent:FindFirstChild("Humanoid"):TakeDamage(19)
		wait(1)


	end
end)

Error code is on line 22

1 answer

✓ Accepted answer

:FindFirstChild() is meant to return either the child if it exists or nil. You can't obviously call :TakeDamage() on nil so you must use an if statement to do this. Also parent should be Parent where I see the Touched connection starting line 19.

Below, I reformed your code starting line 19 to be more correct. It checks if the humanoid exists and if it does, it deals damage as you specified.

-- i am not sure why the indentation is weird
script.Parent.Damage.Touched:Connect(function(p)
    if script.Parent.DMG.Value == true then
        script.Parent.DMG.Value = false
	local humanoid = p.Parent:FindFirstChild("Humanoid")
	if humanoid then
        	humanoid:TakeDamage(19)
	end
        wait(1)
    end
end)

1 comment

0

Idk why it auto indents like that either, but thank you.

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