Attempt to call funtion 'get_name' in base 'null_instance' on a null instance. (Weapon pickup)

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

I followed a tutorial on how to drop and pickup weapons, every time I pickup the weapon it crashes. Also in the debugger it repeats:

get_child: Index p_index = 0 is out of bounds (data.children.size() = 0)

Whenever I don’t have a gun equipped. Any help would be apprieciated, Im kinda new to godot so go easy on me :slight_smile:

If you want to follow the same tutorial to try and help me it’s this one by Garbaj : https://www.youtube.com/watch?v=mzKV0HS3u0A

onready var gun_a_hr = preload("res://Objects/Gun A HR.tscn")
onready var gun_a = preload("res://Objects/Gun A.tscn")
onready var gun_b_hr = preload("res://Objects/Gun B HR.tscn")
onready var gun_b = preload("res://Objects/Gun B.tscn")

func _process(delta):

#Weapon drop and pickup
if reach.is_colliding():
	if reach.get_collider().get_name() == "Gun A":
		weapon_to_spawn = gun_a_hr.instance()
	elif reach.get_collider().get_name() == "Gun B":
		weapon_to_spawn = gun_b_hr.instance()
	else:
		weapon_to_spawn = null
else:
	weapon_to_spawn = null

if hand.get_child(0) != null:
	if hand.get_child(0).get_name() == "Gun A HR":
		weapon_to_drop = gun_a.instance()
	elif hand.get_child(0).get_name() == "Gun B HR":
		weapon_to_drop = gun_b.instance()
else:
	weapon_to_drop = null

if Input.is_action_just_pressed("interact"):
	if weapon_to_spawn != null:
		if hand.get_child(0) != null:
			get_parent().add_child(weapon_to_drop)
			weapon_to_drop.global_transform = hand.global_transform
			weapon_to_drop.dropped = true
			hand.get_child(0).queue_free()
		reach.get_collider().queue_free()
		hand.add_child(weapon_to_spawn)
		weapon_to_spawn.rotation = hand.rotation

#Check if there is weapon in hand and then drop
if Input.is_action_just_pressed("Drop"):
	if hand.get_child(0) != null:
		get_parent().add_child(weapon_to_drop)
		weapon_to_drop.global_transform = hand.global_transform
		weapon_to_drop.dropped = true
		hand.get_child(0).queue_free()
:bust_in_silhouette: Reply From: timothybrentwood

Uhh you shouldn’t be checking collision inside of _process() that should be done inside of _physics_process()… that’s also not just spaghetti code that’s like an entire Italian cuisine…

Your issue is the check if hand.get_child(0) != null:. hand has no children so by trying to grab the zeroth element you’re causing an array out of bounds error. The proper way to check this without causing crashes is by checkingif not hand.get_children().empty(): first.

That’s pretty basic programming… very poorly written code all around. I highly suggest following another tutorial. Check out heartbeast, game endeavor, GDQuest, KidsCanCode, you’ll learn how to do things the proper way with those channels.