scripting_continued.rst 7.9 KB

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