scripting_continued.rst 12 KB

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