scripting.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. .. _doc_scripting:
  2. Scripting
  3. =========
  4. Introduction
  5. ------------
  6. Before Godot 3.0, the only choice for scripting a game was to use
  7. :ref:`GDScript<doc_gdscript>`. Nowadays, Godot has four (yes, four!) official languages
  8. and the ability to add extra scripting languages dynamically!
  9. This is great, mostly due to the large amount of flexibility provided, but
  10. it also makes our work supporting languages more difficult.
  11. The "main" languages in Godot, though, are GDScript and VisualScript. The
  12. main reason to choose them is their level of integration with Godot, as this
  13. makes the experience smoother; both have slick editor integration, while
  14. C# and C++ need to be edited in a separate IDE. If you are a big fan of statically typed languages, go with C# and C++ instead.
  15. GDScript
  16. ~~~~~~~~
  17. :ref:`GDScript<doc_gdscript>` is, as mentioned above, the main language used in Godot.
  18. Using it has some positive points compared to other languages due
  19. to its high integration with Godot:
  20. * It's simple, elegant, and designed to be familiar for users of other languages such as Lua, Python, Squirrel, etc.
  21. * Loads and compiles blazingly fast.
  22. * The editor integration is a pleasure to work with, with code completion for nodes, signals, and many other items pertaining to the scene being edited.
  23. * Has vector types built-in (such as Vectors, transforms, etc.), making it efficient for heavy use of linear algebra.
  24. * Supports multiple threads as efficiently as statically typed languages - one of the limitations that made us avoid VMs such as Lua, Squirrel, etc.
  25. * Uses no garbage collector, so it trades a small bit of automation (most objects are reference counted anyway), by determinism.
  26. * Its dynamic nature makes it easy to optimize sections of code in C++ (via GDNative) if more performance is required, all without recompiling the engine.
  27. If you're undecided and have experience with programming, especially dynamically
  28. typed languages, go for GDScript!
  29. VisualScript
  30. ~~~~~~~~~~~~
  31. Beginning with 3.0, Godot offers :ref:`Visual Scripting<doc_what_is_visual_script>`. This is a
  32. typical implementation of a "blocks and connections" language, but
  33. adapted to how Godot works.
  34. Visual scripting is a great tool for non-programmers, or even for experienced developers
  35. who want to make parts of the code more accessible to others,
  36. like game designers or artists.
  37. It can also be used by programmers to build state machines or custom
  38. visual node workflows - for example, a dialogue system.
  39. .NET / C#
  40. ~~~~~~~~~
  41. As Microsoft's C# is a favorite amongst game developers, we have added
  42. official support for it. C# is a mature language with tons of code
  43. written for it, and support was added thanks to
  44. a generous donation from Microsoft.
  45. It has an excellent tradeoff between performance and ease of use,
  46. although one must be aware of its garbage collector.
  47. Since Godot uses the `Mono <https://mono-project.com>`_ .NET runtime, in theory
  48. any third-party .NET library or framework can be used for scripting in Godot, as
  49. well as any Common Language Infrastructure-compliant programming language, such as
  50. F#, Boo or ClojureCLR. In practice however, C# is the only officially supported .NET option.
  51. GDNative / C++
  52. ~~~~~~~~~~~~~~
  53. Finally, one of our brightest additions for the 3.0 release:
  54. GDNative allows scripting in C++ without needing to recompile (or even
  55. restart) Godot.
  56. Any C++ version can be used, and mixing compiler brands and versions for the
  57. generated shared libraries works perfectly, thanks to our use of an internal C
  58. API Bridge.
  59. This language is the best choice for performance and does not need to be
  60. used throughout an entire game, as other parts can be written in GDScript or Visual
  61. Script. However the API is clear and easy to use as it resembles, mostly,
  62. Godot's actual C++ API.
  63. More languages can be made available through the GDNative interface, but keep in mind
  64. we don't have official support for them.
  65. Scripting a scene
  66. -----------------
  67. For the rest of this tutorial we'll set up a GUI scene consisting of a
  68. button and a label, where pressing the button will update the label. This will
  69. demonstrate:
  70. - Writing a script and attaching it to a node.
  71. - Hooking up UI elements via signals.
  72. - Writing a script that can access other nodes in the scene.
  73. Before continuing, please make sure to read the :ref:`GDScript<doc_gdscript>` reference.
  74. It's a language designed to be simple, and the reference is short, so it will not take more
  75. than a few minutes to get an overview of the concepts.
  76. Scene setup
  77. ~~~~~~~~~~~
  78. Use the "Add Child Node" dialogue accessed from the Scene tab (or by pressing ``Ctrl+A``) to create a hierarchy with the following
  79. nodes:
  80. - Panel
  81. * Label
  82. * Button
  83. The scene tree should look like this:
  84. .. image:: img/scripting_scene_tree.png
  85. Use the 2D editor to position and resize the Button and Label so that they
  86. look like the image below. You can set the text from the Inspector tab.
  87. .. image:: img/label_button_example.png
  88. Finally, save the scene with a name such as ``sayhello.tscn``.
  89. .. _doc_scripting-adding_a_script:
  90. Adding a script
  91. ~~~~~~~~~~~~~~~
  92. Right click on the Panel node, then select "Attach Script" from the context
  93. menu:
  94. .. image:: img/add_script.png
  95. The script creation dialog will pop up. This dialog allows you to set the
  96. script's language, class name, and other relevant options.
  97. In GDScript, the file itself represents the class, so
  98. the class name field is not editable.
  99. The node we're attaching the script to is a panel, so the Inherits field
  100. will automatically be filled in with "Panel". This is what we want, as the
  101. script's goal is to extend the functionality of our panel node.
  102. Finally, enter a path name for the script and select Create:
  103. .. image:: img/script_create.png
  104. The script will then be created and added to the node. You can
  105. see this as an "Open script" icon next to the node in the Scene tab,
  106. as well as in the script property under Inspector:
  107. .. image:: img/script_added.png
  108. To edit the script, select either of these buttons, both of which are highlighted in the above image.
  109. This will bring you to the script editor, where a default template will be included:
  110. .. image:: img/script_template.png
  111. There's not much there. The ``_ready()`` function is called when the
  112. node, and all its children, enters the active scene. **Note:** ``_ready()`` is not
  113. the constructor; the constructor is instead ``_init()``.
  114. The role of the script
  115. ~~~~~~~~~~~~~~~~~~~~~~
  116. A script adds behavior to a node. It is used to control how the node functions
  117. as well as how it interacts with other nodes: children, parent, siblings,
  118. and so on. The local scope of the script is the node. In other words, the script
  119. inherits the functions provided by that node.
  120. .. image:: /img/brainslug.jpg
  121. .. _doc_scripting_handling_a_signal:
  122. Handling a signal
  123. ~~~~~~~~~~~~~~~~~
  124. Signals are "emitted" when some specific kind of action happens, and they can be
  125. connected to any function of any script instance. Signals are used mostly in
  126. GUI nodes, although other nodes have them too, and you can even define custom
  127. signals in your own scripts.
  128. In this step, we'll connect the "pressed" signal to a custom function. Forming
  129. connections is the first part and defining the custom function is the second part.
  130. For the first part, Godot provides two ways to create connections: through a
  131. visual interface the editor provides or through code.
  132. While we will use the code method for the remainder of this tutorial series, let's
  133. cover how the editor interface works for future reference.
  134. Select the Button node in the scene tree and then select the "Node" tab. Next,
  135. make sure that you have "Signals" selected.
  136. .. image:: img/signals.png
  137. If you then select "pressed()" under "BaseButton" and click the "Connect..."
  138. button in the bottom right, you'll open up the connection creation dialogue.
  139. .. image:: img/connect_dialogue.png
  140. In the bottom-left are the key things you need to create a connection: a node
  141. which implements the method you want to trigger (represented here as a
  142. NodePath) and the name of the method to trigger.
  143. The top-left section displays a list of your scene's nodes with the emitting
  144. node's name highlighted in red. Select the "Panel" node here. When you select
  145. a node, the NodePath at the bottom will automatically update to point to a
  146. relative path from the emitting node to the selected node.
  147. By default, the method name will contain the emitting node's name ("Button" in
  148. this case), resulting in ``_on_[EmitterNode]_[signal_name]``. If you do have the
  149. "Make Function" check button checked, then the editor will generate the function
  150. for you before setting up the connection.
  151. And that concludes the guide on how to use the visual interface. However, this
  152. is a scripting tutorial, so for the sake of learning, let's dive into the
  153. manual process!
  154. To accomplish this, we will introduce a function that is probably the most used
  155. by Godot programmers: :ref:`Node.get_node() <class_Node_method_get_node>`.
  156. This function uses paths to fetch nodes anywhere in the scene, relative to the
  157. node that owns the script.
  158. For the sake of convenience, delete everything underneath ``extends Panel``.
  159. You will fill out the rest of the script manually.
  160. Because the Button and Label are siblings under the Panel
  161. where the script is attached, you can fetch the Button by typing
  162. the following underneath the ``_ready()`` function:
  163. .. tabs::
  164. .. code-tab:: gdscript GDScript
  165. func _ready():
  166. get_node("Button")
  167. .. code-tab:: csharp
  168. public override void _Ready()
  169. {
  170. GetNode("Button");
  171. }
  172. Next, write a function which will be called when the button is pressed:
  173. .. tabs::
  174. .. code-tab:: gdscript GDScript
  175. func _on_Button_pressed():
  176. get_node("Label").text = "HELLO!"
  177. .. code-tab:: csharp
  178. public void _OnButtonPressed()
  179. {
  180. GetNode<Label>("Label").Text = "HELLO!";
  181. }
  182. Finally, connect the button's "pressed" signal to ``_ready()`` by
  183. using :ref:`Object.connect() <class_Object_method_connect>`.
  184. .. tabs::
  185. .. code-tab:: gdscript GDScript
  186. func _ready():
  187. get_node("Button").connect("pressed", self, "_on_Button_pressed")
  188. .. code-tab:: csharp
  189. public override void _Ready()
  190. {
  191. GetNode("Button").Connect("pressed", this, nameof(_OnButtonPressed));
  192. }
  193. The final script should look like this:
  194. .. tabs::
  195. .. code-tab:: gdscript GDScript
  196. extends Panel
  197. func _ready():
  198. get_node("Button").connect("pressed", self, "_on_Button_pressed")
  199. func _on_Button_pressed():
  200. get_node("Label").text = "HELLO!"
  201. .. code-tab:: csharp
  202. using Godot;
  203. // IMPORTANT: the name of the class MUST match the filename exactly.
  204. // this is case sensitive!
  205. public class sayhello : Panel
  206. {
  207. public override void _Ready()
  208. {
  209. GetNode("Button").Connect("pressed", this, nameof(_OnButtonPressed));
  210. }
  211. public void _OnButtonPressed()
  212. {
  213. GetNode<Label>("Label").Text = "HELLO!";
  214. }
  215. }
  216. Run the scene and press the button. You should get the following result:
  217. .. image:: img/scripting_hello.png
  218. Why, hello there! Congratulations on scripting your first scene.
  219. .. note::
  220. A common misunderstanding regarding this tutorial is how ``get_node(path)``
  221. works. For a given node, ``get_node(path)`` searches its immediate children.
  222. In the above code, this means that Button must be a child of Panel. If
  223. Button were instead a child of Label, the code to obtain it would be:
  224. .. tabs::
  225. .. code-tab:: gdscript GDScript
  226. # Not for this case,
  227. # but just in case.
  228. get_node("Label/Button")
  229. .. code-tab:: csharp
  230. // Not for this case,
  231. // but just in case.
  232. GetNode("Label/Button")
  233. Also, remember that nodes are referenced by name, not by type.
  234. .. note::
  235. The right-hand panel of the connect dialogue is for binding specific
  236. values to the connected function's parameters. You can add and remove
  237. values of different types.
  238. The code approach also enables this with a 4th ``Array`` parameter that
  239. is empty by default. Feel free to read up on the ``Object.connect``
  240. method for more information.