nodes_and_scene_instances.rst 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. .. _doc_nodes_and_scene_instances:
  2. Nodes and scene instances
  3. =========================
  4. This guide explains how to get nodes, create nodes, add them as a child, and
  5. instantiate scenes from code.
  6. .. seealso::
  7. Check the :ref:`doc_instancing` tutorial to learn about Godot's approach to scene instancing.
  8. Getting nodes
  9. -------------
  10. You can get a reference to a node by calling the :ref:`Node.get_node()
  11. <class_Node_method_get_node>` method. For this to work, the child node must be
  12. present in the scene tree. Getting it in the parent node's ``_ready()`` function
  13. guarantees that.
  14. If, for example, you have a scene tree like this, and you want to get a reference to the
  15. Sprite2D and Camera2D nodes to access them in your script.
  16. .. image:: img/nodes_and_scene_instances_player_scene_example.webp
  17. To do so, you can use the following code.
  18. .. tabs::
  19. .. code-tab:: gdscript GDScript
  20. var sprite2d
  21. var camera2d
  22. func _ready():
  23. sprite2d = get_node("Sprite2D")
  24. camera2d = get_node("Camera2D")
  25. .. code-tab:: csharp
  26. private Sprite2D _sprite2D;
  27. private Camera2D _camera2D;
  28. public override void _Ready()
  29. {
  30. base._Ready();
  31. _sprite2D = GetNode<Sprite2D>("Sprite2D");
  32. _camera2D = GetNode<Camera2D>("Camera2D");
  33. }
  34. Note that you get nodes using their name, not their type. Above, "Sprite2D" and
  35. "Camera2D" are the nodes' names in the scene.
  36. .. image:: img/nodes_and_scene_instances_sprite_node.webp
  37. If you rename the Sprite2D node as Skin in the Scene dock, you have to change the
  38. line that gets the node to ``get_node("Skin")`` in the script.
  39. .. image:: img/nodes_and_scene_instances_sprite_node_renamed.webp
  40. Node paths
  41. ----------
  42. When getting a reference to a node, you're not limited to getting a direct child. The ``get_node()`` function
  43. supports paths, a bit like when working with a file browser. Add a slash to
  44. separate nodes.
  45. Take the following example scene, with the script attached to the UserInterface
  46. node.
  47. .. image:: img/nodes_and_scene_instances_ui_scene_example.webp
  48. To get the AnimationPlayer node, you would use the following code.
  49. .. tabs::
  50. .. code-tab:: gdscript GDScript
  51. var animation_player
  52. func _ready():
  53. animation_player = get_node("ShieldBar/AnimationPlayer")
  54. .. code-tab:: csharp
  55. private AnimationPlayer _animationPlayer;
  56. public override void _Ready()
  57. {
  58. base._Ready();
  59. _animationPlayer = GetNode<AnimationPlayer>("ShieldBar/AnimationPlayer");
  60. }
  61. .. note:: As with file paths, you can use ".." to get a parent node. The best
  62. practice is to avoid doing that though not to break encapsulation.
  63. You can also start the path with a forward
  64. slash to make it absolute, in which case your topmost node would be
  65. "/root", the application's predefined root viewport.
  66. Syntactic sugar
  67. ~~~~~~~~~~~~~~~
  68. You can use two shorthands to shorten your code in GDScript. Firstly, putting the
  69. ``@onready`` annotation before a member variable makes it initialize right before
  70. the ``_ready()`` callback.
  71. .. code-block:: gdscript
  72. @onready var sprite2d = get_node("Sprite2D")
  73. There is also a short notation for ``get_node()``: the dollar sign, "$". You
  74. place it before the name or path of the node you want to get.
  75. .. code-block:: gdscript
  76. @onready var sprite2d = $Sprite2D
  77. @onready var animation_player = $ShieldBar/AnimationPlayer
  78. Creating nodes
  79. --------------
  80. To create a node from code, call its ``new()`` method like for any other
  81. class-based datatype.
  82. You can store the newly created node's reference in a variable and call
  83. ``add_child()`` to add it as a child of the node to which you attached the
  84. script.
  85. .. tabs::
  86. .. code-tab:: gdscript GDScript
  87. var sprite2d
  88. func _ready():
  89. var sprite2d = Sprite2D.new() # Create a new Sprite2D.
  90. add_child(sprite2d) # Add it as a child of this node.
  91. .. code-tab:: csharp
  92. private Sprite2D _sprite2D;
  93. public override void _Ready()
  94. {
  95. base._Ready();
  96. _sprite2D = new Sprite2D(); // Create a new Sprite2D.
  97. AddChild(_sprite2D); // Add it as a child of this node.
  98. }
  99. To delete a node and free it from memory, you can call its ``queue_free()``
  100. method. Doing so queues the node for deletion at the end of the current frame
  101. after it has finished processing. At that point, the engine removes the node from
  102. the scene and frees the object in memory.
  103. .. tabs::
  104. .. code-tab:: gdscript GDScript
  105. sprite2d.queue_free()
  106. .. code-tab:: csharp
  107. _sprite2D.QueueFree();
  108. Before calling ``sprite2d.queue_free()``, the remote scene tree looks like this.
  109. .. image:: img/nodes_and_scene_instances_remote_tree_with_sprite.webp
  110. After the engine freed the node, the remote scene tree doesn't display the
  111. sprite anymore.
  112. .. image:: img/nodes_and_scene_instances_remote_tree_no_sprite.webp
  113. You can alternatively call ``free()`` to immediately destroy the node. You
  114. should do this with care as any reference to it will instantly become ``null``.
  115. We recommend using ``queue_free()`` unless you know what you're doing.
  116. When you free a node, it also frees all its children. Thanks to this, to delete
  117. an entire branch of the scene tree, you only have to free the topmost parent
  118. node.
  119. Instancing scenes
  120. -----------------
  121. Scenes are templates from which you can create as many reproductions as you'd
  122. like. This operation is called instancing, and doing it from code happens in two
  123. steps:
  124. 1. Loading the scene from the local drive.
  125. 2. Creating an instance of the loaded :ref:`PackedScene <class_PackedScene>`
  126. resource.
  127. .. tabs::
  128. .. code-tab:: gdscript GDScript
  129. var scene = load("res://my_scene.tscn")
  130. .. code-tab:: csharp
  131. var scene = GD.Load<PackedScene>("res://MyScene.tscn");
  132. Preloading the scene can improve the user's experience as the load operation
  133. happens when the compiler reads the script and not at runtime. This feature is
  134. only available with GDScript.
  135. .. tabs::
  136. .. code-tab:: gdscript GDScript
  137. var scene = preload("res://my_scene.tscn")
  138. At that point, ``scene`` is a packed scene resource, not a node. To create the
  139. actual node, you need to call :ref:`PackedScene.instantiate()
  140. <class_PackedScene_method_instantiate>`. It returns a tree of nodes that you can use
  141. as a child of your current node.
  142. .. tabs::
  143. .. code-tab:: gdscript GDScript
  144. var instance = scene.instantiate()
  145. add_child(instance)
  146. .. code-tab:: csharp
  147. var instance = scene.Instantiate();
  148. AddChild(instance);
  149. The advantage of this two-step process is you can keep a packed scene loaded and
  150. create new instances on the fly. For example, to quickly instance several
  151. enemies or bullets.