scripting_continued.rst 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. .. _doc_scripting_continued:
  2. Scripting (continued)
  3. =====================
  4. Groups
  5. ------
  6. Groups in Godot work like tags you might have come across in other software.
  7. A node can be added to as many groups as desired. This is a useful feature for
  8. organizing large scenes. There are two ways to add nodes to groups. The
  9. first is from the UI, using the Groups button under the Node panel:
  10. .. image:: img/groups_in_nodes.png
  11. And the second way is from code. The following script would add the current
  12. node to the ``enemies`` group as soon as it appeared in the scene tree.
  13. .. tabs::
  14. .. code-tab:: gdscript GDScript
  15. func _ready():
  16. add_to_group("enemies")
  17. .. code-tab:: csharp
  18. public override void _Ready()
  19. {
  20. base._Ready();
  21. AddToGroup("enemies");
  22. }
  23. This way, if the player is discovered sneaking into a secret base,
  24. all enemies can be notified about its alarm sounding by using
  25. :ref:`SceneTree.call_group() <class_SceneTree_method_call_group>`:
  26. .. tabs::
  27. .. code-tab:: gdscript GDScript
  28. func _on_discovered(): # This is a purely illustrative function.
  29. get_tree().call_group("enemies", "player_was_discovered")
  30. .. code-tab:: csharp
  31. public void _OnDiscovered() // This is a purely illustrative function.
  32. {
  33. GetTree().CallGroup("enemies", "player_was_discovered");
  34. }
  35. The above code calls the function ``player_was_discovered`` on every
  36. member of the group ``enemies``.
  37. It is also possible to get the full list of ``enemies`` nodes by
  38. calling
  39. :ref:`SceneTree.get_nodes_in_group() <class_SceneTree_method_get_nodes_in_group>`:
  40. .. tabs::
  41. .. code-tab:: gdscript GDScript
  42. var enemies = get_tree().get_nodes_in_group("enemies")
  43. .. code-tab:: csharp
  44. var enemies = GetTree().GetNodesInGroup("enemies");
  45. The :ref:`SceneTree <class_SceneTree>` class provides many useful methods,
  46. like interacting with scenes, their node hierarchy and groups of nodes.
  47. It allows you to easily switch scenes or reload them,
  48. to quit the game or pause and unpause it.
  49. It even comes with interesting signals.
  50. So check it out if you have some time!
  51. Notifications
  52. -------------
  53. Godot has a system of notifications. These are usually not needed for
  54. scripting, as it's too low-level and virtual functions are provided for
  55. most of them. It's just good to know they exist. For example,
  56. you may add an
  57. :ref:`Object._notification() <class_Object_method__notification>`
  58. function in your script:
  59. .. tabs::
  60. .. code-tab:: gdscript GDScript
  61. func _notification(what):
  62. match what:
  63. NOTIFICATION_READY:
  64. print("This is the same as overriding _ready()...")
  65. NOTIFICATION_PROCESS:
  66. print("This is the same as overriding _process()...")
  67. .. code-tab:: csharp
  68. public override void _Notification(int what)
  69. {
  70. base._Notification(what);
  71. switch (what)
  72. {
  73. case NotificationReady:
  74. GD.Print("This is the same as overriding _Ready()...");
  75. break;
  76. case NotificationProcess:
  77. var delta = GetProcessDeltaTime();
  78. GD.Print("This is the same as overriding _Process()...");
  79. break;
  80. }
  81. }
  82. The documentation of each class in the :ref:`Class Reference <toc-class-ref>`
  83. shows the notifications it can receive. However, in most cases GDScript
  84. provides simpler overridable functions.
  85. Overridable functions
  86. ---------------------
  87. Such overridable functions, which are described as
  88. follows, can be applied to nodes:
  89. .. tabs::
  90. .. code-tab:: gdscript GDScript
  91. func _enter_tree():
  92. # When the node enters the Scene Tree, it becomes active
  93. # and this function is called. Children nodes have not entered
  94. # the active scene yet. In general, it's better to use _ready()
  95. # for most cases.
  96. pass
  97. func _ready():
  98. # This function is called after _enter_tree, but it ensures
  99. # that all children nodes have also entered the Scene Tree,
  100. # and became active.
  101. pass
  102. func _exit_tree():
  103. # When the node exits the Scene Tree, this function is called.
  104. # Children nodes have all exited the Scene Tree at this point
  105. # and all became inactive.
  106. pass
  107. func _process(delta):
  108. # This function is called every frame.
  109. pass
  110. func _physics_process(delta):
  111. # This is called every physics frame.
  112. pass
  113. .. code-tab:: csharp
  114. public override void _EnterTree()
  115. {
  116. // When the node enters the Scene Tree, it becomes active
  117. // and this function is called. Children nodes have not entered
  118. // the active scene yet. In general, it's better to use _ready()
  119. // for most cases.
  120. base._EnterTree();
  121. }
  122. public override void _Ready()
  123. {
  124. // This function is called after _enter_tree, but it ensures
  125. // that all children nodes have also entered the Scene Tree,
  126. // and became active.
  127. base._Ready();
  128. }
  129. public override void _ExitTree()
  130. {
  131. // When the node exits the Scene Tree, this function is called.
  132. // Children nodes have all exited the Scene Tree at this point
  133. // and all became inactive.
  134. base._ExitTree();
  135. }
  136. public override void _Process(float delta)
  137. {
  138. // This function is called every frame.
  139. base._Process(delta);
  140. }
  141. public override void _PhysicsProcess(float delta)
  142. {
  143. // This is called every physics frame.
  144. base._PhysicsProcess(delta);
  145. }
  146. As mentioned before, it's better to use these functions instead of
  147. the notification system.
  148. Creating nodes
  149. --------------
  150. To create a node from code, call the ``.new()`` method, like for any
  151. other class-based datatype. For example:
  152. .. tabs::
  153. .. code-tab:: gdscript GDScript
  154. var s
  155. func _ready():
  156. s = Sprite.new() # Create a new sprite!
  157. add_child(s) # Add it as a child of this node.
  158. .. code-tab:: csharp
  159. private Sprite _sprite;
  160. public override void _Ready()
  161. {
  162. base._Ready();
  163. _sprite = new Sprite(); // Create a new sprite!
  164. AddChild(_sprite); // Add it as a child of this node.
  165. }
  166. To delete a node, be it inside or outside the scene, ``free()`` must be
  167. used:
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. func _someaction():
  171. s.free() # Immediately removes the node from the scene and frees it.
  172. .. code-tab:: csharp
  173. public void _SomeAction()
  174. {
  175. _sprite.Free(); // Immediately removes the node from the scene and frees it.
  176. }
  177. When a node is freed, it also frees all its child nodes. Because of
  178. this, manually deleting nodes is much simpler than it appears. Free
  179. the base node and everything else in the subtree goes away with it.
  180. A situation might occur where we want to delete a node that
  181. is currently "blocked", because it is emitting a signal or calling a
  182. function. This will crash the game. Running Godot
  183. with the debugger will often catch this case and warn you about it.
  184. The safest way to delete a node is by using
  185. :ref:`Node.queue_free() <class_Node_method_queue_free>`.
  186. This erases the node safely during idle.
  187. .. tabs::
  188. .. code-tab:: gdscript GDScript
  189. func _someaction():
  190. s.queue_free() # Removes the node from the scene and frees it when it becomes safe to do so.
  191. .. code-tab:: csharp
  192. public void _SomeAction()
  193. {
  194. _sprite.QueueFree(); // Removes the node from the scene and frees it when it becomes safe to do so.
  195. }
  196. Instancing scenes
  197. -----------------
  198. Instancing a scene from code is done in two steps. The
  199. first one is to load the scene from your hard drive:
  200. .. tabs::
  201. .. code-tab:: gdscript GDScript
  202. var scene = load("res://myscene.tscn") # Will load when the script is instanced.
  203. .. code-tab:: csharp
  204. var scene = GD.Load<PackedScene>("res://myscene.tscn"); // Will load when the script is instanced.
  205. Preloading it can be more convenient, as it happens at parse
  206. time (GDScript only):
  207. .. tabs::
  208. .. code-tab:: gdscript GDScript
  209. var scene = preload("res://myscene.tscn") # Will load when parsing the script.
  210. But ``scene`` is not yet a node. It's packed in a
  211. special resource called :ref:`PackedScene <class_PackedScene>`.
  212. To create the actual node, the function
  213. :ref:`PackedScene.instance() <class_PackedScene_method_instance>`
  214. must be called. This will return the tree of nodes that can be added to
  215. the active scene:
  216. .. tabs::
  217. .. code-tab:: gdscript GDScript
  218. var node = scene.instance()
  219. add_child(node)
  220. .. code-tab:: csharp
  221. var node = scene.Instance();
  222. AddChild(node);
  223. The advantage of this two-step process is that a packed scene may be
  224. kept loaded and ready to use so that you can create as many
  225. instances as desired. This is especially useful to quickly instance
  226. several enemies, bullets, and other entities in the active scene.
  227. .. _doc_scripting_continued_class_name:
  228. Register scripts as classes
  229. ---------------------------
  230. Godot has a "Script Class" feature to register individual scripts with the
  231. Editor. By default, you can only access unnamed scripts by loading the file
  232. directly.
  233. You can name a script and register it as a type in the editor with the
  234. ``class_name`` keyword followed by the class's name. You may add a comma and an
  235. optional path to an image to use as an icon. You will then find your new type in
  236. the Node or Resource creation dialog.
  237. .. tabs::
  238. .. code-tab:: gdscript GDScript
  239. extends Node
  240. # Declare the class name here
  241. class_name ScriptName, "res://path/to/optional/icon.svg"
  242. func _ready():
  243. var this = ScriptName # reference to the script
  244. var cppNode = MyCppNode.new() # new instance of a class named MyCppNode
  245. cppNode.queue_free()
  246. .. image:: img/script_class_nativescript_example.png
  247. .. warning:: In Godot 3.1:
  248. - Only GDScript and NativeScript, i.e., C++ and other GDNative-powered languages, can register scripts.
  249. - Only GDScript creates global variables for each named script.