scripting.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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, make sure to skim and bookmark the :ref:`GDScript<doc_gdscript>` reference.
  74. It's a language designed to be simple, and the reference is structured into sections to make it
  75. easier to get an overview of the concepts.
  76. Scene setup
  77. ~~~~~~~~~~~
  78. If you still have the "instancing" project open from the previous tutorial, then close that out (Project -> Quit to Project List) and create a New Project.
  79. Use the "Add Child Node" dialogue accessed from the Scene tab (or by pressing :kbd:`Ctrl + A`) to create a hierarchy with the following
  80. nodes:
  81. - Panel
  82. * Label
  83. * Button
  84. The scene tree should look like this:
  85. .. image:: img/scripting_scene_tree.png
  86. Use the 2D editor to position and resize the Button and Label so that they
  87. look like the image below. You can set the text from the Inspector tab.
  88. .. image:: img/label_button_example.png
  89. Finally, save the scene with a name such as ``sayhello.tscn``.
  90. .. _doc_scripting-adding_a_script:
  91. Adding a script
  92. ~~~~~~~~~~~~~~~
  93. Right click on the Panel node, then select "Attach Script" from the context
  94. menu:
  95. .. image:: img/add_script.png
  96. The script creation dialog will pop up. This dialog allows you to set the
  97. script's language, class name, and other relevant options.
  98. In GDScript, the file itself represents the class, so
  99. the class name field is not editable.
  100. The node we're attaching the script to is a panel, so the Inherits field
  101. will automatically be filled in with "Panel". This is what we want, as the
  102. script's goal is to extend the functionality of our panel node.
  103. Finally, enter a path name for the script and select Create:
  104. .. image:: img/script_create.png
  105. The script will then be created and added to the node. You can
  106. see this as an "Open script" icon next to the node in the Scene tab,
  107. as well as in the script property under Inspector:
  108. .. image:: img/script_added.png
  109. To edit the script, select either of these buttons, both of which are highlighted in the above image.
  110. This will bring you to the script editor, where a default template will be included:
  111. .. image:: img/script_template.png
  112. There's not much there. The ``_ready()`` function is called when the
  113. node, and all its children, enters the active scene. **Note:** ``_ready()`` is not
  114. the constructor; the constructor is instead ``_init()``.
  115. The role of the script
  116. ~~~~~~~~~~~~~~~~~~~~~~
  117. A script adds behavior to a node. It is used to control how the node functions
  118. as well as how it interacts with other nodes: children, parent, siblings,
  119. and so on. The local scope of the script is the node. In other words, the script
  120. inherits the functions provided by that node.
  121. .. image:: img/brainslug.jpg
  122. .. _doc_scripting_handling_a_signal:
  123. Handling a signal
  124. ~~~~~~~~~~~~~~~~~
  125. Signals are "emitted" when some specific kind of action happens, and they can be
  126. connected to any function of any script instance. Signals are used mostly in
  127. GUI nodes, although other nodes have them too, and you can even define custom
  128. signals in your own scripts.
  129. In this step, we'll connect the "pressed" signal to a custom function. Forming
  130. connections is the first part and defining the custom function is the second part.
  131. For the first part, Godot provides two ways to create connections: through a
  132. visual interface the editor provides or through code.
  133. While we will use the code method for the remainder of this tutorial series, let's
  134. cover how the editor interface works for future reference.
  135. Select the Button node in the scene tree and then select the "Node" tab. Next,
  136. make sure that you have "Signals" selected.
  137. .. image:: img/signals.png
  138. If you then select "pressed()" under "BaseButton" and click the "Connect..."
  139. button in the bottom right, you'll open up the connection creation dialogue.
  140. .. image:: img/connect_dialogue.png
  141. The top of the dialogue displays a list of your scene's nodes with the emitting
  142. node's name highlighted in blue. Select the "Panel" node here.
  143. The bottom of the dialogue shows the name of the method that will be created.
  144. By default, the method name will contain the emitting node's name ("Button" in
  145. this case), resulting in ``_on_[EmitterNode]_[signal_name]``.
  146. And that concludes the guide on how to use the visual interface. However, this
  147. is a scripting tutorial, so for the sake of learning, let's dive into the
  148. manual process!
  149. To accomplish this, we will introduce a function that is probably the most used
  150. by Godot programmers: :ref:`Node.get_node() <class_Node_method_get_node>`.
  151. This function uses paths to fetch nodes anywhere in the scene, relative to the
  152. node that owns the script.
  153. For the sake of convenience, delete everything underneath ``extends Panel``.
  154. You will fill out the rest of the script manually.
  155. Because the Button and Label are siblings under the Panel
  156. where the script is attached, you can fetch the Button by typing
  157. the following underneath the ``_ready()`` function:
  158. .. tabs::
  159. .. code-tab:: gdscript GDScript
  160. func _ready():
  161. get_node("Button")
  162. .. code-tab:: csharp
  163. public override void _Ready()
  164. {
  165. GetNode("Button");
  166. }
  167. Next, write a function which will be called when the button is pressed:
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. func _on_Button_pressed():
  171. get_node("Label").text = "HELLO!"
  172. .. code-tab:: csharp
  173. public void _OnButtonPressed()
  174. {
  175. GetNode<Label>("Label").Text = "HELLO!";
  176. }
  177. Finally, connect the button's "pressed" signal to ``_on_Button_pressed()`` by
  178. using :ref:`Object.connect() <class_Object_method_connect>`.
  179. .. tabs::
  180. .. code-tab:: gdscript GDScript
  181. func _ready():
  182. get_node("Button").connect("pressed", self, "_on_Button_pressed")
  183. .. code-tab:: csharp
  184. public override void _Ready()
  185. {
  186. GetNode("Button").Connect("pressed", this, nameof(_OnButtonPressed));
  187. }
  188. The final script should look like this:
  189. .. tabs::
  190. .. code-tab:: gdscript GDScript
  191. extends Panel
  192. func _ready():
  193. get_node("Button").connect("pressed", self, "_on_Button_pressed")
  194. func _on_Button_pressed():
  195. get_node("Label").text = "HELLO!"
  196. .. code-tab:: csharp
  197. using Godot;
  198. // IMPORTANT: the name of the class MUST match the filename exactly.
  199. // this is case sensitive!
  200. public class sayhello : Panel
  201. {
  202. public override void _Ready()
  203. {
  204. GetNode("Button").Connect("pressed", this, nameof(_OnButtonPressed));
  205. }
  206. public void _OnButtonPressed()
  207. {
  208. GetNode<Label>("Label").Text = "HELLO!";
  209. }
  210. }
  211. Run the scene and press the button. You should get the following result:
  212. .. image:: img/scripting_hello.png
  213. Why, hello there! Congratulations on scripting your first scene.
  214. .. note::
  215. A common misunderstanding regarding this tutorial is how ``get_node(path)``
  216. works. For a given node, ``get_node(path)`` searches its immediate children.
  217. In the above code, this means that Button must be a child of Panel. If
  218. Button were instead a child of Label, the code to obtain it would be:
  219. .. tabs::
  220. .. code-tab:: gdscript GDScript
  221. # Not for this case,
  222. # but just in case.
  223. get_node("Label/Button")
  224. .. code-tab:: csharp
  225. // Not for this case,
  226. // but just in case.
  227. GetNode("Label/Button")
  228. Also, remember that nodes are referenced by name, not by type.
  229. .. note::
  230. The 'advanced' panel of the connect dialogue is for binding specific
  231. values to the connected function's parameters. You can add and remove
  232. values of different types.
  233. The code approach also enables this with a 4th ``Array`` parameter that
  234. is empty by default. Feel free to read up on the ``Object.connect``
  235. method for more information.