How to make reusable Nodes (with hierarchy)

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


since I created some Nodes with children

some for the main player, some for enemies

  • how do I use them between scenes ?
  • how do I instantiate these dynamically (like enemies and such) ?

thanks for enlightening me on this

:bust_in_silhouette: Reply From: timothybrentwood

Right click the top level node that you want to make reusable then press the Save Branch as Scene option. Save it as “scene1.tscn” (for explanation purposes). You can now drag and drop that scene1.tscn into any other scene and scene1.tscn will become a child of the scene it is dropped on.

Or through code:

var load_scene_one = load("res://scene1.tscn") # should be the path to where scene1.tscn lives
# note you can drag and drop scene1.tscn to the script and it will give you the path

func create_new_scene_at_position(the_position):
    var new_instance = load_scene_one.instance()

    # if you don't add it as a child to something it will be an orphan and be lost

    # now you can work with it like any other node
    new_scene.position = the_position 

Edit: a video explaining this concept:

ok, but do I heve to take care of duplicate myself ?
I mean what if I load 10x the same scene, does goto deal with resources cache or something ?

phil1234 | 2021-05-19 17:46

:bust_in_silhouette: Reply From: scrubswithnosleeves

This is the recommended way to instantiate nodes.

var bullet_TSCN = preload("res://YOUR_PATH")

In a fucntion:

if Input.is_action_just_pressed("shoot"):
		var bullet_ins = bullet_TSCN.instance()
		bullet_ins.global_position = self.global_position