Checking To See If There's Children

I’m checking to see if the player has anything in their backpack using the code below, but I keep getting attempt to index nil with ‘GetChildren’

if #player.Backpack:FindFirstChild("Hatching"):GetChildren() > 0 then

All I’m trying to do is see if there’s any children in “Hatching,” what’s wrong with the way I’m doing it?

Full script

while true do
	wait(1)
	for i, player in pairs(game.Players:GetPlayers())do
		if #player.Backpack:FindFirstChild("Hatching"):GetChildren() > 0 then
			playerEggs = player.Backpack:FindFirstChild("Hatching"):GetChildren()
			for i, egg in pairs(playerEggs)do
				if egg.HatchingTime.Value > 0 then
					egg.HatchingTime.Value = egg.HatchingTime.Value - 1
				end
			end
		end
	end
end

Thanks!

Could you please explain how you are indexing the player and whether you are using indexing it on the client or server? Another thing; could you confirm that there is a Instance named “Hatching” parented in the player’s backpack?

1 Like

I’m using it on the server. Yes, “Hatching” is something that is present in every player. The script works fine if the “Children” of “Hatching” load in before the script runs.

This will clear up your error messages assuming you handle the return values, but your problem is that hatching does not exist at the execution time of your script.

--[[
	returns 1 if there is atleast 1 child
	returns 0 if there are no children
	returns -1 if Hatching container does not exist yet
]]--
function CheckHatchingChildren(Player)
	local Hatching = Player.Backpack:FindFirstChild("Hatching");
	if Hatching then
		if #Hatching:GetChildren() > 0 then
			return 1;
		end
		return 0;
	end
	return -1;
end

``
1 Like

This should fix your issue then:

if #player:WaitForChild("Backpack"):WaitForChild(“Hatching"):GetChildren() > 0 then
1 Like

There’s a double child word in the function name.

Is there a better way to do what I’m doing? It works like one out of five times but the other times it errors with infinite yield.

You must replace this:

For this:

Hatching = player.Backpack:WaitForChild("Hatching")
if #Hatching:GetChildren() > 0 then
1 Like