node.get_child() throws out_of_bounds error

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By connordechart

I am currently having issues with this code from the internet.

onready var reach = $Player/Pivot2/Camera/Reach
onready var hand = $Player/Hand    
onready var axemodel = preload('res://Scenes/Axe.tscn')

func _process(_delta):
    	if reach.is_colliding():
    		if reach.get_collider().get_name() == "Axe":
    			weapon_to_spawn = axemodel.instance()
    			weapon_to_spawn = null
    		weapon_to_spawn = null
    	if hand.get_child(0) != null:
    		if hand.get_child(0).get_name() == "Axe":
    			weapon_to_drop = axemodel.instance()
    		weapon_to_drop = null
    	if Input.is_action_just_pressed("TakeItem"):
    		if weapon_to_spawn != null:
    			if hand.get_child(null) != null:
    				weapon_to_drop.global_transform = hand.global_transform
    				weapon_to_drop.dropped = true
    			weapon_to_spawn.rotation = hand.rotation

What this script is trying to do is search for nearby items that can be grabbed, and if you press E on them you will equip it. If you have any item in your hand you will drop it and equip a new one.

However this line right here throws an error:

if hand.get_child(0) != null:


   E 0:00:05.648   get_child: Index p_index = 0 is out of bounds (data.children.size() = 0).
  <C++ Source>  scene/main/node.cpp:1296 @ get_child()
  <Stack Trace> @ _process()

I can’t get my head around this and i don’t know how to fix it as it seems an engine error but what do i know. Sorry if this is a dumb question i’m new to Godot

:bust_in_silhouette: Reply From: jgodfrey

The error is generated when the child array doesn’t contain any elements. You can’t ask about the 1st element ([0]) if there are no elements.

Generally, the fix for that would be to first ensure that the array contains something prior to attempting to access the first element.

Here’s one way to do that:

if child.size() > 0:
    # child array has at least one element, so you can safely access child[0] now
:bust_in_silhouette: Reply From: Matt2626

This error happens when the child doesn’t have any elements inside, so you should check if there is any element inside this child.
you could try this

if hand.get_child_count() > 0:

to check if there is a element inside the hand