Script assigning variables, cannot understand how/where

Godot Version

4.3

Question

I’m making a top-down 2D roguelike.
I have a function in my main player script that swaps the weapon you are currently holding with the weapon in your inventory, if you have one.

However, if you are not holding a weapon, but have one in your inventory (which can happen, as you can also drop your weapon), then the code I currently have does not work correctly and it assigns both the weapon in your hand and the weapon in your inventory to be the same, which then causes problems down the line.

My weapons are built as different scenes that are then added as children to the player so they can access them. It works perfectly fine outside of this weapon swapping issue.

The player accesses the weapon once it is assigned into the “weapon” variable. And then it assigns the weapon.holder to be itself so it can then access the weapons shoot() function

I’ve tried various different configurations of my code, but cannot get it to work.

I’ve also split the change weapon function into two parts to help with debugging but cannot find a solution.

I can provide the rest of my code if that helps.

I’m quite new to Gdscript, so any help would be appreciated.

func _change_weapon(weapon_to_swap, current_weapon):

# Takes the weapon in the holster, changes our current weapon to that
# and then puts the weapon we had, back in the holster
if current_weapon:
	remove_child(current_weapon)
	add_child(weapon_to_swap)
	weapon = weapon_to_swap
	inventory.weapon_in_holster = current_weapon
	weapon.weapon_holder = self

	
if current_weapon == null:
	print("FIX BUG")
	# STILL NEEDS FIXING, ATM it causes the weapon in your inventory
	# and your current weapon to be the same 
	remove_child(current_weapon)
	add_child(weapon_to_swap)
	weapon = weapon_to_swap  
	inventory.weapon_in_holster = current_weapon
	weapon.weapon_holder = self

So we’re just swapping between current_weapon and holster weapons, if any? And these are nodes where weapons will be added as children? Can these nodes be completely clean “anchor” points so that they only ever have zero or one children?

func _change_weapons() -> void:
	#assuming *current_weapon* and *inventory.weapon_in_holster* are nodes purely for holding weapons
	var current: Node = null
	if current_weapon.get_children_count(): #we have a weapon in hand
		current = current_weapon.get_child(0)
	var holstered: Node = null
	if inventory.weapon_in_holster.get_children_count(): #we have a weapon in holster
		holstered = inventory.weapon_in_holster.get_child(0)
	
	if current: current.reparent(inventory.weapon_in_holster)
	if holstered: holstered.reparent(current_weapon)
	return

This should work if its set up like I assumed. The current_weapon and weapon_in_holster nodes should have 0 or 1 children, and if they have any children, we remember the first one (should be only one). Then we use node.reparent to swap the node(s).