Attempt to index nil with 'MaxHealth'

I’ve been getting this error and I’m not sure what they mean or how to fix it. The problem is: attempt to index nil with ‘MaxHealth’

I’m fine to answer any questions you have.

local debounce = true

function onTouched(hit)
	if hit.Parent:findFirstChild("Humanoid").MaxHealth == 100 then
		hit.Parent:findFirstChild("Humanoid").MaxHealth = 500
		while true do
			hit.Parent:findFirstChild("Humanoid").Health += 5
		end
	end
end

script.Parent.Touched:connect(onTouched)

function onTouch(hit) 
local d = hit.Parent:GetChildren() 
for i=1, #d do 
if (d[i].className == "Accessory") then d[i]:remove() 
end 
end
end 

script.Parent.Touched:connect(onTouched)
1 Like

Hey, FindFirstChild returns nil if it doesnt find the child. Thus, in your condition you should check if it returned nil. If not, then you can proceed with the health condition like this:

if workspace:FindFirstChild(“abc”) and workspace.abc.Health == 25 then

end

Edit: got ninja’d

As mentioned in other posts, make sure you do a check to make sure there is a humanoid in the hit’s parent, because if there isn’t, it returns nil.

Before you do any of your if-statements in your onTouched function, do this one first.

if hit.Parent:FindFirstChild("Humanoid") then
     -- your code
end

This if-statement ensures that there is a child called “humanoid”.

as the others said, make sure there is a Humanoid. Also, make sure to properly capitalize FindFirstChild(). You have it as findFirstChild() roblox is very sensitive about these type of things.

This function has a lot of errors.

function onTouched(hit)
	if hit.Parent:findFirstChild("Humanoid").MaxHealth == 100 then -- You need to check if hit has any humanoids before comparing it
		hit.Parent:findFirstChild("Humanoid").MaxHealth = 500 -- Instead of repeating the code, why not save it to a variable to shorten it?
        -- Instead of using a loop, you can simply regenerate humanoid instantly
		while true do
			hit.Parent:findFirstChild("Humanoid").Health += 5
		end
	end
end
function onTouched(hit)
    local hum = hit:FindFirstChildOfClass('Humanoid')
	if hum then
        if hum.MaxHealth == 100 then
            hum.MaxHealth = 500
            hum.Health = hum.MaxHealth -- 500
        end
    end
end
function onTouch(hit) 
local d = hit.Parent:GetChildren() 
for i=1, #d do 
if (d[i].className == "Accessory") then d[i]:remove() 
end 
end
end 

improvements:

  • Use the “Tab” button on your keyboard to make the code more readable
  • Use: IsA() instead of instance.ClassName
  • Use :Destroy() instead of :Remove(), this feature is deprecated
function onTouch(hit) 
    local d = hit.Parent:GetChildren() 
    for i=1, #d do 
        if (d[i]:IsA("Accessory")) then
            d[i]:Destroy()
        end 
    end
end 

If there’s anything weird, and because I’m using the translator, sry xd

Extra:

Instance | Roblox Creator Documentation (deprecated)
Instance | Roblox Creator Documentation

3 Likes