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

Everything to do with my humanoid is nil! Can someone please help?

Hey guys, so I asked another question a few hours ago, and a problem popped up through it.

So I have this script, which is supposed to be like an oxygen tank, and when you reach 0 oxygen, it hurts you.

local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChild("Humanoid")
local air = script.Parent


while wait(1) do
	if Character:FindFirstChild("SmallAir") then
		air.Value = air.Value - 1
			if air.Value > 0 then
				print(air.Value.." air remaining.")
			else
				print("No air remaining!")
				Humanoid.Health = Humanoid.Health - 10
		end
	end
end

However, it always gives me the error of "attempt to index nil with 'Health'" It seems that this is not just a problem with the health, because I've tried to do print(Humanoid.Parent.Name) and it tells me that Parent is the nil value. Any specific reason?

5 comments

0

Script or localscript?

0

localscript

0

Try "Humanoid:TakeDamage(10)"

0

Now it says that TakeDamage is nil

0

look at my answer it may help you

2 answers

✓ Accepted answer

So the problem is that you got "or Player.CharacterAdded:Wait()", that doesn't return Character. You can do something like this:

local Player = game:GetService("Players").LocalPlayer
local Humanoid = Player.Character:WaitForChild("Humanoid")
local air = script.Parent


while wait(1) do
	if Player.Character:FindFirstChild("SmallAir") then
		air.Value = air.Value - 1
		if air.Value > 0 then
			print(air.Value.." air remaining.")
		else
			print("No air remaining!")
			Humanoid.Health = Humanoid.Health - 10
		end
	end
end

3 comments

0

Thank you!!

0

Np

0

What's wrong with Player.CharacterAdded:Wait()? doesn't it just wait until the character is added in case it doesn't exist?

The Humanoid tends to take some time to be added into your Character, so in this case you would use WaitForChild instead of FindFirstChild. FindFirstChild will get the first child with the same name it can find, which if it hasn't been added yet, will result in nil. WaitForChild in the other hand will wait until an Instance with the same name is added, making it useful in situations where a part takes time to be there. Be sure to only use WaitForChild when necessary though, since it will stop your entire script until it finds the part. (unless you add a second statement to how many time you want to wait until it gives up, like this for example: local Humanoid = Character:WaitForChild("Humanoid",5) )

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