I didn't know replace_by
, but maybe that's what you want:
var new_weapon_scene = load("res://other_weapon.tscn")
var new_weapon = new_weapon_scene.instance()
_current_weapon.replace_by(new_weapon)
Or, if not using replace_by
:
var new_weapon_scene = load("res://other_weapon.tscn")
var new_weapon = new_weapon_scene.instance()
var weapon_parent = _current_weapon.get_parent()
weapon_parent.remove_child(_current_weapon)
_current_weapon.call_deferred("free")
new_weapon.name = _current_weapon.name
weapon_parent.add_child(new_weapon)
_current_weapon = new_weapon
Note that I'm assuming you don't need to remember each weapon's state, so this solution destroys the previous weapon and instances the new one.
If you want to memorize state, then you'll have to not free
them after removing from the tree and store them in a member variable instead (like an inventory) until the player switches back to them, instead of instancing each time.
Also, if the weapon has connected signals, you may need to disconnect/reconnect them.