Best practices in regards to instancing nodes?

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

Hey, I’m quite new to godot and was wondering if the way I’m currently instancing my things is reasonable.

export var equipWeaponPath = "res://foobar"
var weapon setget _set_weapon
func _ready():
    var weaponInstance = load(equipWeapon).instance()
    _set_weapon(weaponInstance)

func _set_weapon(arg):
    if weapon:
        weapon.queue_free()
    add_child(arg)
    weapon = arg

So the reason why I’m doing this is so I can change weapons during runtime, just by doing something like…

func _this_runs_every_frame():
    if condition:
        _set_weapon(new_weapon)

…and easily change my weapon.

This seems to me like a pretty convoluted way to do something seemingly simple. Am I overthinking? What other ways are there to do this, if any?

:bust_in_silhouette: Reply From: JimArtificer

Another alternative is to show/hide the weapons instead of creating and destroying them. That way you can load all of them at the same time instead of hitting the hard drive during gameplay. This could be useful if you are intending for the player to switch weapons frequently or for the number of weapons to be finite.

That is a great idea. This would imply preloading everything into some global state/handler and calling some _get_weapon_from_global() as needed?

wndr | 2020-07-22 14:52

You might be able to simplify it even more by having all of the weapons as children of the same node, and call hide() on the current weapon before calling show() on the next one.

Later, if you want to, you could have it play an animation before/after those function calls to represent equipping the item.

JimArtificer | 2020-07-22 23:16

Cool, I will implement some variations of these things and see what works best. Thanks for the feedback.

wndr | 2020-07-23 06:47