gdscript_basics.rst 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  1. .. _doc_gdscript:
  2. GDScript basics
  3. ===============
  4. Introduction
  5. ------------
  6. *GDScript* is a high-level, dynamically typed programming language used to
  7. create content. It uses a syntax similar to
  8. `Python <https://en.wikipedia.org/wiki/Python_%28programming_language%29>`_
  9. (blocks are indent-based and many keywords are similar). Its goal is
  10. to be optimized for and tightly integrated with Godot Engine, allowing great
  11. flexibility for content creation and integration.
  12. History
  13. ~~~~~~~
  14. .. note::
  15. Documentation about GDScript's history has been moved to the
  16. :ref:`Frequently Asked Questions <doc_faq_what_is_gdscript>`.
  17. Example of GDScript
  18. ~~~~~~~~~~~~~~~~~~~
  19. Some people can learn better by taking a look at the syntax, so
  20. here's a simple example of how GDScript looks.
  21. ::
  22. # Everything after "#" is a comment.
  23. # A file is a class!
  24. # (optional) class definition:
  25. class_name MyClass
  26. # Inheritance:
  27. extends BaseClass
  28. # (optional) icon to show in the editor dialogs:
  29. @icon("res://path/to/optional/icon.svg")
  30. # Member variables.
  31. var a = 5
  32. var s = "Hello"
  33. var arr = [1, 2, 3]
  34. var dict = {"key": "value", 2: 3}
  35. var other_dict = {key = "value", other_key = 2}
  36. var typed_var: int
  37. var inferred_type := "String"
  38. # Constants.
  39. const ANSWER = 42
  40. const THE_NAME = "Charly"
  41. # Enums.
  42. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  43. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  44. # Built-in vector types.
  45. var v2 = Vector2(1, 2)
  46. var v3 = Vector3(1, 2, 3)
  47. # Functions.
  48. func some_function(param1, param2, param3):
  49. const local_const = 5
  50. if param1 < local_const:
  51. print(param1)
  52. elif param2 > 5:
  53. print(param2)
  54. else:
  55. print("Fail!")
  56. for i in range(20):
  57. print(i)
  58. while param2 != 0:
  59. param2 -= 1
  60. match param3:
  61. 3:
  62. print("param3 is 3!")
  63. _:
  64. print("param3 is not 3!")
  65. var local_var = param1 + 3
  66. return local_var
  67. # Functions override functions with the same name on the base/super class.
  68. # If you still want to call them, use "super":
  69. func something(p1, p2):
  70. super(p1, p2)
  71. # It's also possible to call another function in the super class:
  72. func other_something(p1, p2):
  73. super.something(p1, p2)
  74. # Inner class
  75. class Something:
  76. var a = 10
  77. # Constructor
  78. func _init():
  79. print("Constructed!")
  80. var lv = Something.new()
  81. print(lv.a)
  82. If you have previous experience with statically typed languages such as
  83. C, C++, or C# but never used a dynamically typed one before, it is advised you
  84. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  85. Language
  86. --------
  87. In the following, an overview is given to GDScript. Details, such as which
  88. methods are available to arrays or other objects, should be looked up in
  89. the linked class descriptions.
  90. Identifiers
  91. ~~~~~~~~~~~
  92. Any string that restricts itself to alphabetic characters (``a`` to
  93. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  94. as an identifier. Additionally, identifiers must not begin with a digit.
  95. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  96. Keywords
  97. ~~~~~~~~
  98. The following is the list of keywords supported by the language. Since
  99. keywords are reserved words (tokens), they can't be used as identifiers.
  100. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  101. as listed in the following sections are also reserved.
  102. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  103. in case you want to take a look under the hood.
  104. +------------+---------------------------------------------------------------------------------------------------------------+
  105. | Keyword | Description |
  106. +============+===============================================================================================================+
  107. | if | See `if/else/elif`_. |
  108. +------------+---------------------------------------------------------------------------------------------------------------+
  109. | elif | See `if/else/elif`_. |
  110. +------------+---------------------------------------------------------------------------------------------------------------+
  111. | else | See `if/else/elif`_. |
  112. +------------+---------------------------------------------------------------------------------------------------------------+
  113. | for | See for_. |
  114. +------------+---------------------------------------------------------------------------------------------------------------+
  115. | while | See while_. |
  116. +------------+---------------------------------------------------------------------------------------------------------------+
  117. | match | See match_. |
  118. +------------+---------------------------------------------------------------------------------------------------------------+
  119. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  120. +------------+---------------------------------------------------------------------------------------------------------------+
  121. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  122. +------------+---------------------------------------------------------------------------------------------------------------+
  123. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  124. +------------+---------------------------------------------------------------------------------------------------------------+
  125. | return | Returns a value from a function. |
  126. +------------+---------------------------------------------------------------------------------------------------------------+
  127. | class | Defines a class. |
  128. +------------+---------------------------------------------------------------------------------------------------------------+
  129. | class_name | Defines the script as a globally accessible class with the specified name. |
  130. +------------+---------------------------------------------------------------------------------------------------------------+
  131. | extends | Defines what class to extend with the current class. |
  132. +------------+---------------------------------------------------------------------------------------------------------------+
  133. | is | Tests whether a variable extends a given class, or is of a given built-in type. |
  134. +------------+---------------------------------------------------------------------------------------------------------------+
  135. | as | Cast the value to a given type if possible. |
  136. +------------+---------------------------------------------------------------------------------------------------------------+
  137. | self | Refers to current class instance. |
  138. +------------+---------------------------------------------------------------------------------------------------------------+
  139. | signal | Defines a signal. |
  140. +------------+---------------------------------------------------------------------------------------------------------------+
  141. | func | Defines a function. |
  142. +------------+---------------------------------------------------------------------------------------------------------------+
  143. | static | Defines a static function. Static member variables are not allowed. |
  144. +------------+---------------------------------------------------------------------------------------------------------------+
  145. | const | Defines a constant. |
  146. +------------+---------------------------------------------------------------------------------------------------------------+
  147. | enum | Defines an enum. |
  148. +------------+---------------------------------------------------------------------------------------------------------------+
  149. | var | Defines a variable. |
  150. +------------+---------------------------------------------------------------------------------------------------------------+
  151. | breakpoint | Editor helper for debugger breakpoints. |
  152. +------------+---------------------------------------------------------------------------------------------------------------+
  153. | preload | Preloads a class or variable. See `Classes as resources`_. |
  154. +------------+---------------------------------------------------------------------------------------------------------------+
  155. | await | Waits for a signal or a coroutine to finish. See `Awaiting for signals`_. |
  156. +------------+---------------------------------------------------------------------------------------------------------------+
  157. | yield | Previously used for coroutines. Kept as keyword for transition. |
  158. +------------+---------------------------------------------------------------------------------------------------------------+
  159. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  160. +------------+---------------------------------------------------------------------------------------------------------------+
  161. | void | Used to represent that a function does not return any value. |
  162. +------------+---------------------------------------------------------------------------------------------------------------+
  163. | PI | PI constant. |
  164. +------------+---------------------------------------------------------------------------------------------------------------+
  165. | TAU | TAU constant. |
  166. +------------+---------------------------------------------------------------------------------------------------------------+
  167. | INF | Infinity constant. Used for comparisons and as result of calculations. |
  168. +------------+---------------------------------------------------------------------------------------------------------------+
  169. | NAN | NAN (not a number) constant. Used as impossible result from calculations. |
  170. +------------+---------------------------------------------------------------------------------------------------------------+
  171. Operators
  172. ~~~~~~~~~
  173. The following is the list of supported operators and their precedence.
  174. +------------------------------------------------------------------------+-----------------------------------------+
  175. | **Operator** | **Description** |
  176. +------------------------------------------------------------------------+-----------------------------------------+
  177. | ``x[index]`` | Subscription (highest priority) |
  178. +------------------------------------------------------------------------+-----------------------------------------+
  179. | ``x.attribute`` | Attribute reference |
  180. +------------------------------------------------------------------------+-----------------------------------------+
  181. | ``foo()`` | Function call |
  182. +------------------------------------------------------------------------+-----------------------------------------+
  183. | ``is`` | Instance type checker |
  184. +------------------------------------------------------------------------+-----------------------------------------+
  185. | ``~`` | Bitwise NOT |
  186. +------------------------------------------------------------------------+-----------------------------------------+
  187. | ``-x`` | Negative / Unary negation |
  188. +------------------------------------------------------------------------+-----------------------------------------+
  189. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  190. | | |
  191. | | These operators have the same behavior |
  192. | | as C++. Integer division is truncated |
  193. | | rather than returning a fractional |
  194. | | number, and the % operator is only |
  195. | | available for ints ("fmod" for floats) |
  196. +------------------------------------------------------------------------+-----------------------------------------+
  197. | ``+`` | Addition / Concatenation of arrays |
  198. +------------------------------------------------------------------------+-----------------------------------------+
  199. | ``-`` | Subtraction |
  200. +------------------------------------------------------------------------+-----------------------------------------+
  201. | ``<<`` ``>>`` | Bit shifting |
  202. +------------------------------------------------------------------------+-----------------------------------------+
  203. | ``&`` | Bitwise AND |
  204. +------------------------------------------------------------------------+-----------------------------------------+
  205. | ``^`` | Bitwise XOR |
  206. +------------------------------------------------------------------------+-----------------------------------------+
  207. | ``|`` | Bitwise OR |
  208. +------------------------------------------------------------------------+-----------------------------------------+
  209. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  210. +------------------------------------------------------------------------+-----------------------------------------+
  211. | ``in`` | Content test |
  212. +------------------------------------------------------------------------+-----------------------------------------+
  213. | ``not`` | Boolean NOT |
  214. +------------------------------------------------------------------------+-----------------------------------------+
  215. | ``and`` | Boolean AND |
  216. +------------------------------------------------------------------------+-----------------------------------------+
  217. | ``or`` | Boolean OR |
  218. +------------------------------------------------------------------------+-----------------------------------------+
  219. | ``if x else`` | Ternary if/else |
  220. +------------------------------------------------------------------------+-----------------------------------------+
  221. | ``as`` | Type casting |
  222. +------------------------------------------------------------------------+-----------------------------------------+
  223. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` ``<<=`` ``>>=`` | Assignment (lowest priority) |
  224. +------------------------------------------------------------------------+-----------------------------------------+
  225. Literals
  226. ~~~~~~~~
  227. +--------------------------+----------------------------------------+
  228. | **Literal** | **Type** |
  229. +--------------------------+----------------------------------------+
  230. | ``45`` | Base 10 integer |
  231. +--------------------------+----------------------------------------+
  232. | ``0x8f51`` | Base 16 (hexadecimal) integer |
  233. +--------------------------+----------------------------------------+
  234. | ``0b101010`` | Base 2 (binary) integer |
  235. +--------------------------+----------------------------------------+
  236. | ``3.14``, ``58.1e-10`` | Floating-point number (real) |
  237. +--------------------------+----------------------------------------+
  238. | ``"Hello"``, ``"Hi"`` | Strings |
  239. +--------------------------+----------------------------------------+
  240. | ``"""Hello"""`` | Multiline string |
  241. +--------------------------+----------------------------------------+
  242. | ``&"name"`` | :ref:`StringName <class_StringName>` |
  243. +--------------------------+----------------------------------------+
  244. | ``^"Node/Label"`` | :ref:`NodePath <class_NodePath>` |
  245. +--------------------------+----------------------------------------+
  246. | ``$NodePath`` | Shorthand for ``get_node("NodePath")`` |
  247. +--------------------------+----------------------------------------+
  248. Integers and floats can have their numbers separated with ``_`` to make them more readable.
  249. The following ways to write numbers are all valid::
  250. 12_345_678 # Equal to 12345678.
  251. 3.141_592_7 # Equal to 3.1415927.
  252. 0x8080_0000_ffff # Equal to 0x80800000ffff.
  253. 0b11_00_11_00 # Equal to 0b11001100.
  254. Annotations
  255. ~~~~~~~~~~~
  256. There are some special tokens in GDScript that act like keywords but are not,
  257. they are *annotations* instead. Every annotation start with the ``@`` character
  258. and is specified by a name.
  259. Those affect how the script is treated by external tools and usually don't
  260. change the behavior.
  261. For instance, you can use it to export a value to the editor::
  262. @export_range(1, 100, 1, "or_greater")
  263. var ranged_var: int = 50
  264. Annotations can be specified one per line or all in the same line. They affect
  265. the next statement that isn't an annotation. Annotations can have arguments sent
  266. between parentheses and separated by commas.
  267. Both of these are the same::
  268. @export_file("*.png")
  269. @remote
  270. var x
  271. @export_file("*.png") @remote var x
  272. Here's the list of available annotations:
  273. +------------------------------+---------------------------------------------------------------------------------------------------+
  274. | **Annotation** | **Description** |
  275. +------------------------------+---------------------------------------------------------------------------------------------------+
  276. | ``@tool`` | Enable the `Tool mode`_. |
  277. +------------------------------+---------------------------------------------------------------------------------------------------+
  278. | ``@onready`` | Defer initialization of variable until the node is in the tree. See `Onready annotation`_. |
  279. +------------------------------+---------------------------------------------------------------------------------------------------+
  280. | ``@icon(path)`` | Set the class icon to show in editor. To be used together with the ``class_name`` keyword. |
  281. +------------------------------+---------------------------------------------------------------------------------------------------+
  282. | ``@master`` | RPC modifiers. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  283. | | |
  284. | ``@puppet`` | |
  285. | | |
  286. | ``@remote`` | |
  287. | | |
  288. | ``@mastersync`` | |
  289. | | |
  290. | ``@puppetsync`` | |
  291. | | |
  292. | ``@remotesync`` | |
  293. +------------------------------+---------------------------------------------------------------------------------------------------+
  294. | ``@export`` | Export hints for the editor. See :ref:`doc_gdscript_exports`. |
  295. | | |
  296. | ``@export_enum`` | |
  297. | | |
  298. | ``@export_file`` | |
  299. | | |
  300. | ``@export_dir`` | |
  301. | | |
  302. | ``@export_global_file`` | |
  303. | | |
  304. | ``@export_global_dir`` | |
  305. | | |
  306. | ``@export_multiline`` | |
  307. | | |
  308. | ``@export_placeholder`` | |
  309. | | |
  310. | ``@export_range`` | |
  311. | | |
  312. | ``@export_exp_range`` | |
  313. | | |
  314. | ``@export_exp_easing`` | |
  315. | | |
  316. | ``@export_color_no_alpha`` | |
  317. | | |
  318. | ``@export_node_path`` | |
  319. | | |
  320. | ``@export_flags`` | |
  321. | | |
  322. | ``@export_flags_2d_render`` | |
  323. | | |
  324. | ``@export_flags_2d_physics`` | |
  325. | | |
  326. | ``@export_flags_3d_render`` | |
  327. | | |
  328. | ``@export_flags_3d_physics`` | |
  329. +------------------------------+---------------------------------------------------------------------------------------------------+
  330. Comments
  331. ~~~~~~~~
  332. Anything from a ``#`` to the end of the line is ignored and is
  333. considered a comment.
  334. ::
  335. # This is a comment.
  336. .. _doc_gdscript_builtin_types:
  337. Built-in types
  338. --------------
  339. Built-in types are stack-allocated. They are passed as values. This means a copy
  340. is created on each assignment or when passing them as arguments to functions.
  341. The only exceptions are ``Array``\ s and ``Dictionaries``, which are passed by
  342. reference so they are shared. (Packed arrays such as ``PackedByteArray`` are still
  343. passed as values.)
  344. Basic built-in types
  345. ~~~~~~~~~~~~~~~~~~~~
  346. A variable in GDScript can be assigned to several built-in types.
  347. null
  348. ^^^^
  349. ``null`` is an empty data type that contains no information and can not
  350. be assigned any other value.
  351. :ref:`bool <class_bool>`
  352. ^^^^^^^^^^^^^^^^^^^^^^^^
  353. Short for "boolean", it can only contain ``true`` or ``false``.
  354. :ref:`int <class_int>`
  355. ^^^^^^^^^^^^^^^^^^^^^^
  356. Short for "integer", it stores whole numbers (positive and negative).
  357. It is stored as a 64-bit value, equivalent to "int64_t" in C++.
  358. :ref:`float <class_float>`
  359. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  360. Stores real numbers, including decimals, using floating-point values.
  361. It is stored as a 64-bit value, equivalent to "double" in C++.
  362. Note: Currently, data structures such as Vector2, Vector3, and
  363. PackedFloat32Array store 32-bit single-precision "float" values.
  364. :ref:`String <class_String>`
  365. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  366. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_.
  367. Strings can contain the following escape sequences:
  368. +---------------------+---------------------------------+
  369. | **Escape sequence** | **Expands to** |
  370. +---------------------+---------------------------------+
  371. | ``\n`` | Newline (line feed) |
  372. +---------------------+---------------------------------+
  373. | ``\t`` | Horizontal tab character |
  374. +---------------------+---------------------------------+
  375. | ``\r`` | Carriage return |
  376. +---------------------+---------------------------------+
  377. | ``\a`` | Alert (beep/bell) |
  378. +---------------------+---------------------------------+
  379. | ``\b`` | Backspace |
  380. +---------------------+---------------------------------+
  381. | ``\f`` | Formfeed page break |
  382. +---------------------+---------------------------------+
  383. | ``\v`` | Vertical tab character |
  384. +---------------------+---------------------------------+
  385. | ``\"`` | Double quote |
  386. +---------------------+---------------------------------+
  387. | ``\'`` | Single quote |
  388. +---------------------+---------------------------------+
  389. | ``\\`` | Backslash |
  390. +---------------------+---------------------------------+
  391. | ``\uXXXX`` | Unicode codepoint ``XXXX`` |
  392. | | (hexadecimal, case-insensitive) |
  393. +---------------------+---------------------------------+
  394. Also, using ``\`` followed by a newline inside a string will allow you to continue it in the next line, without
  395. inserting a newline character in the string itself.
  396. GDScript also supports :ref:`doc_gdscript_printf`.
  397. :ref:`StringName <class_StringName>`
  398. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  399. An immutable string that allows only one instance of each name. They are slower to
  400. create and may result in waiting for locks when multithreading. In exchange, they're
  401. very fast to compare, which makes them good candidates for dictionary keys.
  402. :ref:`NodePath <class_NodePath>`
  403. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  404. A pre-parsed path to a node or a node property. They are useful to interact with
  405. the tree to get a node, or affecting properties like with :ref:`Tweens <class_Tween>`.
  406. Vector built-in types
  407. ~~~~~~~~~~~~~~~~~~~~~
  408. :ref:`Vector2 <class_Vector2>`
  409. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  410. 2D vector type containing ``x`` and ``y`` fields. Can also be
  411. accessed as an array.
  412. :ref:`Vector2i <class_Vector2i>`
  413. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  414. Same as a Vector2 but the components are integers. Useful for representing
  415. items in a 2D grid.
  416. :ref:`Rect2 <class_Rect2>`
  417. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  418. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  419. Also contains an ``end`` field which is ``position + size``.
  420. :ref:`Vector3 <class_Vector3>`
  421. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  422. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  423. be accessed as an array.
  424. :ref:`Vector3i <class_Vector3i>`
  425. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  426. Same as Vector3 but the components are integers. Can be use for indexing items
  427. in a 3D grid.
  428. :ref:`Transform2D <class_Transform2D>`
  429. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  430. 3×2 matrix used for 2D transforms.
  431. :ref:`Plane <class_Plane>`
  432. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  433. 3D Plane type in normalized form that contains a ``normal`` vector field
  434. and a ``d`` scalar distance.
  435. :ref:`Quat <class_Quat>`
  436. ^^^^^^^^^^^^^^^^^^^^^^^^
  437. Quaternion is a datatype used for representing a 3D rotation. It's
  438. useful for interpolating rotations.
  439. :ref:`AABB <class_AABB>`
  440. ^^^^^^^^^^^^^^^^^^^^^^^^
  441. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  442. and ``size``. Also contains an ``end`` field which is
  443. ``position + size``.
  444. :ref:`Basis <class_Basis>`
  445. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  446. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  447. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  448. vectors.
  449. :ref:`Transform <class_Transform>`
  450. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  451. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  452. ``origin``.
  453. Engine built-in types
  454. ~~~~~~~~~~~~~~~~~~~~~
  455. :ref:`Color <class_Color>`
  456. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  457. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  458. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  459. :ref:`NodePath <class_NodePath>`
  460. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  461. Compiled path to a node used mainly in the scene system. It can be
  462. easily assigned to, and from, a String.
  463. :ref:`RID <class_RID>`
  464. ^^^^^^^^^^^^^^^^^^^^^^
  465. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  466. :ref:`Object <class_Object>`
  467. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  468. Base class for anything that is not a built-in type.
  469. Container built-in types
  470. ~~~~~~~~~~~~~~~~~~~~~~~~
  471. :ref:`Array <class_Array>`
  472. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  473. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  474. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  475. Negative indices count from the end.
  476. ::
  477. var arr = []
  478. arr = [1, 2, 3]
  479. var b = arr[1] # This is 2.
  480. var c = arr[arr.size() - 1] # This is 3.
  481. var d = arr[-1] # Same as the previous line, but shorter.
  482. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  483. arr.append(4) # Array is now ["Hi!", 2, 3, 4].
  484. GDScript arrays are allocated linearly in memory for speed.
  485. Large arrays (more than tens of thousands of elements) may however cause
  486. memory fragmentation. If this is a concern, special types of
  487. arrays are available. These only accept a single data type. They avoid memory
  488. fragmentation and use less memory, but are atomic and tend to run slower than generic
  489. arrays. They are therefore only recommended to use for large data sets:
  490. - :ref:`PackedByteArray <class_PackedByteArray>`: An array of bytes (integers from 0 to 255).
  491. - :ref:`PackedInt32Array <class_PackedInt32Array>`: An array of 32-bit integers.
  492. - :ref:`PackedInt64Array <class_PackedInt64Array>`: An array of 64-bit integers.
  493. - :ref:`PackedFloat32Array <class_PackedFloat32Array>`: An array of 32-bit floats.
  494. - :ref:`PackedFloat64Array <class_PackedFloat64Array>`: An array of 64-bit floats.
  495. - :ref:`PackedStringArray <class_PackedStringArray>`: An array of strings.
  496. - :ref:`PackedVector2Array <class_PackedVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  497. - :ref:`PackedVector3Array <class_PackedVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  498. - :ref:`PackedColorArray <class_PackedColorArray>`: An array of :ref:`Color <class_Color>` objects.
  499. :ref:`Dictionary <class_Dictionary>`
  500. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  501. Associative container which contains values referenced by unique keys.
  502. ::
  503. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  504. d["Hi!"] = 0
  505. d = {
  506. 22: "value",
  507. "some_key": 2,
  508. "other_key": [2, 3, 4],
  509. "more_key": "Hello"
  510. }
  511. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  512. and doesn't use quotes to mark string keys (making for slightly less to write).
  513. However, keys written in this form can't start with a digit (like any GDScript
  514. identifier).
  515. ::
  516. var d = {
  517. test22 = "value",
  518. some_key = 2,
  519. other_key = [2, 3, 4],
  520. more_key = "Hello"
  521. }
  522. To add a key to an existing dictionary, access it like an existing key and
  523. assign to it::
  524. var d = {} # Create an empty Dictionary.
  525. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  526. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  527. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
  528. var test = 4
  529. # Prints "hello" by indexing the dictionary with a dynamic key.
  530. # This is not the same as `d.test`. The bracket syntax equivalent to
  531. # `d.test` is `d["test"]`.
  532. print(d[test])
  533. .. note::
  534. The bracket syntax can be used to access properties of any
  535. :ref:`class_Object`, not just Dictionaries. Keep in mind it will cause a
  536. script error when attempting to index a non-existing property. To avoid
  537. this, use the :ref:`Object.get() <class_Object_method_get>` and
  538. :ref:`Object.set() <class_Object_method_set>` methods instead.
  539. :ref:`Signal <class_Signal>`
  540. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  541. A signal is a message that can be emitted by an object to those who want to
  542. listen to it. The Signal type can be used for passing the emitter around.
  543. Signals are better used by getting them from actual objects, e.g. ``$Button.button_up``.
  544. :ref:`Callable <class_Callable>`
  545. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  546. Contains an object and a function, which is useful for passing functions as
  547. values (e.g. when connecting to signals).
  548. Getting a method as a member returns a callable.``var x = $Sprite2D.rotate``
  549. will set the value of ``x`` to a callable with ``$Sprite2D`` as the object and
  550. ``rotate`` as the method.
  551. You can call it using the ``call`` method: ``x.call(PI)``.
  552. Data
  553. ----
  554. Variables
  555. ~~~~~~~~~
  556. Variables can exist as class members or local to functions. They are
  557. created with the ``var`` keyword and may, optionally, be assigned a
  558. value upon initialization.
  559. ::
  560. var a # Data type is 'null' by default.
  561. var b = 5
  562. var c = 3.8
  563. var d = b + c # Variables are always initialized in order.
  564. Variables can optionally have a type specification. When a type is specified,
  565. the variable will be forced to have always that same type, and trying to assign
  566. an incompatible value will raise an error.
  567. Types are specified in the variable declaration using a ``:`` (colon) symbol
  568. after the variable name, followed by the type.
  569. ::
  570. var my_vector2: Vector2
  571. var my_node: Node = Sprite2D.new()
  572. If the variable is initialized within the declaration, the type can be inferred, so
  573. it's possible to omit the type name::
  574. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
  575. var my_node := Sprite2D.new() # 'my_node' is of type 'Sprite2D'.
  576. Type inference is only possible if the assigned value has a defined type, otherwise
  577. it will raise an error.
  578. Valid types are:
  579. - Built-in types (Array, Vector2, int, String, etc.).
  580. - Engine classes (Node, Resource, Reference, etc.).
  581. - Constant names if they contain a script resource (``MyScript`` if you declared ``const MyScript = preload("res://my_script.gd")``).
  582. - Other classes in the same script, respecting scope (``InnerClass.NestedClass`` if you declared ``class NestedClass`` inside the ``class InnerClass`` in the same scope).
  583. - Script classes declared with the ``class_name`` keyword.
  584. - Autoloads registered as singletons.
  585. Casting
  586. ^^^^^^^
  587. Values assigned to typed variables must have a compatible type. If it's needed to
  588. coerce a value to be of a certain type, in particular for object types, you can
  589. use the casting operator ``as``.
  590. Casting between object types results in the same object if the value is of the
  591. same type or a subtype of the cast type.
  592. ::
  593. var my_node2D: Node2D
  594. my_node2D = $Sprite2D as Node2D # Works since Sprite2D is a subtype of Node2D.
  595. If the value is not a subtype, the casting operation will result in a ``null`` value.
  596. ::
  597. var my_node2D: Node2D
  598. my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.
  599. For built-in types, they will be forcibly converted if possible, otherwise the
  600. engine will raise an error.
  601. ::
  602. var my_int: int
  603. my_int = "123" as int # The string can be converted to int.
  604. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.
  605. Casting is also useful to have better type-safe variables when interacting with
  606. the scene tree::
  607. # Will infer the variable to be of type Sprite2D.
  608. var my_sprite := $Character as Sprite2D
  609. # Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
  610. ($AnimPlayer as AnimationPlayer).play("walk")
  611. Constants
  612. ~~~~~~~~~
  613. Constants are values you cannot change when the game is running.
  614. Their value must be known at compile-time. Using the
  615. ``const`` keyword allows you to give a constant value a name. Trying to assign a
  616. value to a constant after it's declared will give you an error.
  617. We recommend using constants whenever a value is not meant to change.
  618. ::
  619. const A = 5
  620. const B = Vector2(20, 20)
  621. const C = 10 + 20 # Constant expression.
  622. const D = Vector2(20, 30).x # Constant expression: 20.
  623. const E = [1, 2, 3, 4][0] # Constant expression: 1.
  624. const F = sin(20) # 'sin()' can be used in constant expressions.
  625. const G = x + 20 # Invalid; this is not a constant expression!
  626. const H = A + 20 # Constant expression: 25 (`A` is a constant).
  627. Although the type of constants is inferred from the assigned value, it's also
  628. possible to add explicit type specification::
  629. const A: int = 5
  630. const B: Vector2 = Vector2()
  631. Assigning a value of an incompatible type will raise an error.
  632. You can also create constants inside a function, which is useful to name local
  633. magic values.
  634. .. note::
  635. Since objects, arrays and dictionaries are passed by reference, constants are "flat".
  636. This means that if you declare a constant array or dictionary, it can still
  637. be modified afterwards. They can't be reassigned with another value though.
  638. Enums
  639. ^^^^^
  640. Enums are basically a shorthand for constants, and are pretty useful if you
  641. want to assign consecutive integers to some constant.
  642. If you pass a name to the enum, it will put all the keys inside a constant
  643. dictionary of that name.
  644. .. important:: In Godot 3.1 and later, keys in a named enum are not registered
  645. as global constants. They should be accessed prefixed by the
  646. enum's name (``Name.KEY``); see an example below.
  647. ::
  648. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  649. # Is the same as:
  650. const TILE_BRICK = 0
  651. const TILE_FLOOR = 1
  652. const TILE_SPIKE = 2
  653. const TILE_TELEPORT = 3
  654. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  655. # Is the same as:
  656. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  657. # Access values with State.STATE_IDLE, etc.
  658. Functions
  659. ~~~~~~~~~
  660. Functions always belong to a `class <Classes_>`_. The scope priority for
  661. variable look-up is: local → class member → global. The ``self`` variable is
  662. always available and is provided as an option for accessing class members, but
  663. is not always required (and should *not* be sent as the function's first
  664. argument, unlike Python).
  665. ::
  666. func my_function(a, b):
  667. print(a)
  668. print(b)
  669. return a + b # Return is optional; without it 'null' is returned.
  670. A function can ``return`` at any point. The default return value is ``null``.
  671. Functions can also have type specification for the arguments and for the return
  672. value. Types for arguments can be added in a similar way to variables::
  673. func my_function(a: int, b: String):
  674. pass
  675. If a function argument has a default value, it's possible to infer the type::
  676. func my_function(int_arg := 42, String_arg := "string"):
  677. pass
  678. The return type of the function can be specified after the arguments list using
  679. the arrow token (``->``)::
  680. func my_int_function() -> int:
  681. return 0
  682. Functions that have a return type **must** return a proper value. Setting the
  683. type as ``void`` means the function doesn't return anything. Void functions can
  684. return early with the ``return`` keyword, but they can't return any value.
  685. ::
  686. void_function() -> void:
  687. return # Can't return a value.
  688. .. note:: Non-void functions must **always** return a value, so if your code has
  689. branching statements (such as an ``if``/``else`` construct), all the
  690. possible paths must have a return. E.g., if you have a ``return``
  691. inside an ``if`` block but not after it, the editor will raise an
  692. error because if the block is not executed, the function won't have a
  693. valid value to return.
  694. Referencing functions
  695. ^^^^^^^^^^^^^^^^^^^^^
  696. Functions are first-class items in terms of the Callable object. Referencing a
  697. function by name without calling it will automatically generate the proper
  698. callable. This can be used to pass functions as arguments.
  699. ::
  700. func map(arr: Array, function: Callable) -> Array:
  701. var result = []
  702. for item in arr:
  703. result.push_back(function.call(item))
  704. return result
  705. func add1(value: int) -> int:
  706. return value + 1;
  707. func _ready() -> void:
  708. var my_array = [1, 2, 3]
  709. var plus_one = map(my_array, add1)
  710. print(plus_one) # Prints [2, 3, 4].
  711. .. note:: Callables **must** be called with the ``call`` method. You cannot use
  712. the ``()`` operator directly. This behavior is implemented to avoid
  713. performance issues on direct function calls.
  714. Static functions
  715. ^^^^^^^^^^^^^^^^
  716. A function can be declared static. When a function is static, it has no
  717. access to the instance member variables or ``self``. This is mainly
  718. useful to make libraries of helper functions::
  719. static func sum2(a, b):
  720. return a + b
  721. Statements and control flow
  722. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  723. Statements are standard and can be assignments, function calls, control
  724. flow structures, etc (see below). ``;`` as a statement separator is
  725. entirely optional.
  726. Expressions
  727. ^^^^^^^^^^^
  728. Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be a
  729. statement too, though only calls are reasonable to use as statements since other expressions don't have side effects.
  730. Expressions return values that can be assigned to valid targets. Operands to some operator can be another
  731. expression. An assignment is not an expression and thus does not return any value.
  732. Here are some examples of expressions::
  733. 2 + 2 # Binary operation.
  734. -5 # Unary operation.
  735. "okay" if x > 4 else "not okay" # Ternary operation.
  736. x # Identifier representing variable or constant.
  737. x.a # Attribute access.
  738. x[4] # Subscript access.
  739. x > 2 or x < 5 # Comparisons and logic operators.
  740. x == y + 2 # Equality test.
  741. do_something() # Function call.
  742. [1, 2, 3] # Array definition.
  743. {A = 1, B = 2} # Dictionary definition.
  744. preload("res://icon.png) # Preload builtin function.
  745. self # Reference to current instance.
  746. Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side of
  747. an assignment.
  748. if/else/elif
  749. ^^^^^^^^^^^^
  750. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  751. Parenthesis around conditions are allowed, but not required. Given the
  752. nature of the tab-based indentation, ``elif`` can be used instead of
  753. ``else``/``if`` to maintain a level of indentation.
  754. ::
  755. if [expression]:
  756. statement(s)
  757. elif [expression]:
  758. statement(s)
  759. else:
  760. statement(s)
  761. Short statements can be written on the same line as the condition::
  762. if 1 + 1 == 2: return 2 + 2
  763. else:
  764. var x = 3 + 3
  765. return x
  766. Sometimes, you might want to assign a different initial value based on a
  767. boolean expression. In this case, ternary-if expressions come in handy::
  768. var x = [value] if [expression] else [value]
  769. y += 3 if y < 10 else -1
  770. while
  771. ^^^^^
  772. Simple loops are created by using ``while`` syntax. Loops can be broken
  773. using ``break`` or continued using ``continue``:
  774. ::
  775. while [expression]:
  776. statement(s)
  777. for
  778. ^^^
  779. To iterate through a range, such as an array or table, a *for* loop is
  780. used. When iterating over an array, the current array element is stored in
  781. the loop variable. When iterating over a dictionary, the *key* is stored
  782. in the loop variable.
  783. ::
  784. for x in [5, 7, 11]:
  785. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  786. var dict = {"a": 0, "b": 1, "c": 2}
  787. for i in dict:
  788. print(dict[i]) # Prints 0, then 1, then 2.
  789. for i in range(3):
  790. statement # Similar to [0, 1, 2] but does not allocate an array.
  791. for i in range(1, 3):
  792. statement # Similar to [1, 2] but does not allocate an array.
  793. for i in range(2, 8, 2):
  794. statement # Similar to [2, 4, 6] but does not allocate an array.
  795. for c in "Hello":
  796. print(c) # Iterate through all characters in a String, print every letter on new line.
  797. for i in 3:
  798. statement # Similar to range(3).
  799. for i in 2.2:
  800. statement # Similar to range(ceil(2.2)).
  801. match
  802. ^^^^^
  803. A ``match`` statement is used to branch execution of a program.
  804. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  805. Basic syntax::
  806. match [expression]:
  807. [pattern](s):
  808. [block]
  809. [pattern](s):
  810. [block]
  811. [pattern](s):
  812. [block]
  813. **Crash-course for people who are familiar with switch statements**:
  814. 1. Replace ``switch`` with ``match``.
  815. 2. Remove ``case``.
  816. 3. Remove any ``break``\ s.
  817. 4. Change ``default`` to a single underscore.
  818. **Control flow**:
  819. The patterns are matched from top to bottom.
  820. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  821. You can use ``continue`` to stop execution in the current block and check for an additional match in the patterns below it.
  822. There are 6 pattern types:
  823. - Constant pattern
  824. Constant primitives, like numbers and strings::
  825. match x:
  826. 1:
  827. print("We are number one!")
  828. 2:
  829. print("Two are better than one!")
  830. "test":
  831. print("Oh snap! It's a string!")
  832. - Variable pattern
  833. Matches the contents of a variable/enum::
  834. match typeof(x):
  835. TYPE_REAL:
  836. print("float")
  837. TYPE_STRING:
  838. print("text")
  839. TYPE_ARRAY:
  840. print("array")
  841. - Wildcard pattern
  842. This pattern matches everything. It's written as a single underscore.
  843. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages::
  844. match x:
  845. 1:
  846. print("It's one!")
  847. 2:
  848. print("It's one times two!")
  849. _:
  850. print("It's not 1 or 2. I don't care to be honest.")
  851. - Binding pattern
  852. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  853. It's especially useful in array and dictionary patterns::
  854. match x:
  855. 1:
  856. print("It's one!")
  857. 2:
  858. print("It's one times two!")
  859. var new_var:
  860. print("It's not 1 or 2, it's ", new_var)
  861. - Array pattern
  862. Matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  863. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  864. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``.
  865. Every subpattern has to be comma-separated.
  866. ::
  867. match x:
  868. []:
  869. print("Empty array")
  870. [1, 3, "test", null]:
  871. print("Very specific array")
  872. [var start, _, "test"]:
  873. print("First element is ", start, ", and the last is \"test\"")
  874. [42, ..]:
  875. print("Open ended array")
  876. - Dictionary pattern
  877. Works in the same way as the array pattern. Every key has to be a constant pattern.
  878. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  879. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``.
  880. Every subpattern has to be comma separated.
  881. If you don't specify a value, then only the existence of the key is checked.
  882. A value pattern is separated from the key pattern with a ``:``.
  883. ::
  884. match x:
  885. {}:
  886. print("Empty dict")
  887. {"name": "Dennis"}:
  888. print("The name is Dennis")
  889. {"name": "Dennis", "age": var age}:
  890. print("Dennis is ", age, " years old.")
  891. {"name", "age"}:
  892. print("Has a name and an age, but it's not Dennis :(")
  893. {"key": "godotisawesome", ..}:
  894. print("I only checked for one entry and ignored the rest")
  895. - Multiple patterns
  896. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them.
  897. ::
  898. match x:
  899. 1, 2, 3:
  900. print("It's 1 - 3")
  901. "Sword", "Splash potion", "Fist":
  902. print("Yep, you've taken damage")
  903. Classes
  904. ~~~~~~~
  905. By default, all script files are unnamed classes. In this case, you can only
  906. reference them using the file's path, using either a relative or an absolute
  907. path. For example, if you name a script file ``character.gd``::
  908. # Inherit from 'Character.gd'.
  909. extends "res://path/to/character.gd"
  910. # Load character.gd and create a new node instance from it.
  911. var Character = load("res://path/to/character.gd")
  912. var character_node = Character.new()
  913. .. _doc_gdscript_basics_class_name:
  914. Registering named classes
  915. ~~~~~~~~~~~~~~~~~~~~~~~~~
  916. Instead, you can give your class a name to register it as a new type in Godot's
  917. editor. For that, you use the ``class_name`` keyword. You can optionally use
  918. the ``@icon`` annotation with a path to an image, to use it as an icon. Your
  919. class will then appear with its new icon in the editor::
  920. # Item.gd
  921. extends Node
  922. class_name Item
  923. @icon("res://interface/icons/item.png")
  924. .. image:: img/class_name_editor_register_example.png
  925. Here's a class file example:
  926. ::
  927. # Saved as a file named 'character.gd'.
  928. class_name Character
  929. var health = 5
  930. func print_health():
  931. print(health)
  932. func print_this_script_three_times():
  933. print(get_script())
  934. print(ResourceLoader.load("res://character.gd"))
  935. print(Character)
  936. If you want to use ``extends`` too, you can keep both on the same line::
  937. class_name MyNode extends Node
  938. .. note:: Godot's class syntax is compact: it can only contain member variables or
  939. functions. You can use static functions, but not static member variables. In the
  940. same way, the engine initializes variables every time you create an instance,
  941. and this includes arrays and dictionaries. This is in the spirit of thread
  942. safety, since scripts can be initialized in separate threads without the user
  943. knowing.
  944. Inheritance
  945. ^^^^^^^^^^^
  946. A class (stored as a file) can inherit from:
  947. - A global class.
  948. - Another class file.
  949. - An inner class inside another class file.
  950. Multiple inheritance is not allowed.
  951. Inheritance uses the ``extends`` keyword::
  952. # Inherit/extend a globally available class.
  953. extends SomeClass
  954. # Inherit/extend a named class file.
  955. extends "somefile.gd"
  956. # Inherit/extend an inner class in another file.
  957. extends "somefile.gd".SomeInnerClass
  958. To check if a given instance inherits from a given class,
  959. the ``is`` keyword can be used::
  960. # Cache the enemy class.
  961. const Enemy = preload("enemy.gd")
  962. # [...]
  963. # Use 'is' to check inheritance.
  964. if entity is Enemy:
  965. entity.apply_damage()
  966. To call a function in a *super class* (i.e. one ``extend``-ed in your current
  967. class), user the ``super`` keyword::
  968. super(args)
  969. This is especially useful because functions in extending classes replace
  970. functions with the same name in their super classes. If you still want to
  971. call them, you can use ``super``::
  972. func some_func(x):
  973. super(x) # Calls the same function on the super class.
  974. If you need to call a different function from the super class, you can specify
  975. the function name with the attribute operator::
  976. func overriding():
  977. return 0 # This overrides the method in the base class.
  978. func dont_override():
  979. return super.overriding() # This calls the method as defined in the base class.
  980. Class Constructor
  981. ^^^^^^^^^^^^^^^^^
  982. The class constructor, called on class instantiation, is named ``_init``. If you
  983. want to call the base class constructor, you can also use the ``super`` syntax.
  984. Note that every class has an implicit constructor that it's always called
  985. (defining the default values of class variables). ``super`` is used to call the
  986. explicit constructor::
  987. func _init(arg):
  988. super("some_default", arg) # Call the custom base constructor.
  989. This is better explained through examples. Consider this scenario::
  990. # State.gd (inherited class).
  991. var entity = null
  992. var message = null
  993. func _init(e=null):
  994. entity = e
  995. func enter(m):
  996. message = m
  997. # Idle.gd (inheriting class).
  998. extends "State.gd"
  999. func _init(e=null, m=null):
  1000. super(e)
  1001. # Do something with 'e'.
  1002. message = m
  1003. There are a few things to keep in mind here:
  1004. 1. If the inherited class (``State.gd``) defines a ``_init`` constructor that takes
  1005. arguments (``e`` in this case), then the inheriting class (``Idle.gd``) *must*
  1006. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``State.gd``.
  1007. 2. ``Idle.gd`` can have a different number of arguments than the base class ``State.gd``.
  1008. 3. In the example above, ``e`` passed to the ``State.gd`` constructor is the same ``e`` passed
  1009. in to ``Idle.gd``.
  1010. 4. If ``Idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  1011. to the ``State.gd`` base class, even if it does nothing. This brings us to the fact that you
  1012. can pass expressions to the base constructor as well, not just variables. eg.::
  1013. # Idle.gd
  1014. func _init():
  1015. super(5)
  1016. Inner classes
  1017. ^^^^^^^^^^^^^
  1018. A class file can contain inner classes. Inner classes are defined using the
  1019. ``class`` keyword. They are instanced using the ``ClassName.new()``
  1020. function.
  1021. ::
  1022. # Inside a class file.
  1023. # An inner class in this class file.
  1024. class SomeInnerClass:
  1025. var a = 5
  1026. func print_value_of_a():
  1027. print(a)
  1028. # This is the constructor of the class file's main class.
  1029. func _init():
  1030. var c = SomeInnerClass.new()
  1031. c.print_value_of_a()
  1032. .. _doc_gdscript_classes_as_resources:
  1033. Classes as resources
  1034. ^^^^^^^^^^^^^^^^^^^^
  1035. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  1036. must be loaded from disk to access them in other classes. This is done using
  1037. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  1038. class resource is done by calling the ``new`` function on the class object::
  1039. # Load the class resource when calling load().
  1040. var my_class = load("myclass.gd")
  1041. # Preload the class only once at compile time.
  1042. const MyClass = preload("myclass.gd")
  1043. func _init():
  1044. var a = MyClass.new()
  1045. a.some_function()
  1046. Exports
  1047. ~~~~~~~
  1048. .. note::
  1049. Documentation about exports has been moved to :ref:`doc_gdscript_exports`.
  1050. .. _doc_gdscript_tool_mode:
  1051. Properties
  1052. ~~~~~~~~~~
  1053. Sometimes you want a class' member variable to do more than just hold data and actually perform
  1054. some validation or computation whenever its value change. It may also be desired to
  1055. encapsulate its access in some way.
  1056. For this, GDScript provides a special syntax to define properties using the ``set`` and ``get``
  1057. keywords after a variable declaration. Then you can define a code block that will be executed
  1058. when the variable is accessed or assigned.
  1059. Example::
  1060. var milliseconds: int = 0
  1061. var seconds: int:
  1062. get:
  1063. return milliseconds / 1000
  1064. set(value):
  1065. milliseconds = value * 1000
  1066. Using the variable name inside its own setter or getter will directly access the underlying member, so it
  1067. won't generate infinite recursion and saves you from explicitly declaring another variable::
  1068. signal changed(new_value)
  1069. var warns_when_changed = "some value":
  1070. get:
  1071. return warns_when_changed
  1072. set(value):
  1073. changed.emit(value)
  1074. warns_when_changed = value
  1075. This backing member variable is not created if you don't use it.
  1076. .. note::
  1077. Unlike ``setget`` in previous Godot versions, the properties setter and getter are **always** called,
  1078. even when accessed inside the same class (with or without prefixing with ``self.``). This makes the behavior
  1079. consistent. If you need direct access to the value, use another variable for direct access and make the property
  1080. code use that name.
  1081. In case you want to split the code from the variable declaration or you need to share the code across multiple properties,
  1082. you can use a different notation to use existing class functions::
  1083. var my_prop:
  1084. get = get_my_prop, set = set_my_prop
  1085. This can also be done in the same line.
  1086. Tool mode
  1087. ~~~~~~~~~
  1088. By default, scripts don't run inside the editor and only the exported
  1089. properties can be changed. In some cases, it is desired that they do run
  1090. inside the editor (as long as they don't execute game code or manually
  1091. avoid doing so). For this, the ``@tool`` annotation exists and must be
  1092. placed at the top of the file::
  1093. @tool
  1094. extends Button
  1095. func _ready():
  1096. print("Hello")
  1097. See :ref:`doc_running_code_in_the_editor` for more information.
  1098. .. warning:: Be cautious when freeing nodes with ``queue_free()`` or ``free()``
  1099. in a tool script (especially the script's owner itself). As tool
  1100. scripts run their code in the editor, misusing them may lead to
  1101. crashing the editor.
  1102. Memory management
  1103. ~~~~~~~~~~~~~~~~~
  1104. If a class inherits from :ref:`class_Reference`, then instances will be
  1105. freed when no longer in use. No garbage collector exists, just
  1106. reference counting. By default, all classes that don't define
  1107. inheritance extend **Reference**. If this is not desired, then a class
  1108. must inherit :ref:`class_Object` manually and must call ``instance.free()``. To
  1109. avoid reference cycles that can't be freed, a ``weakref`` function is
  1110. provided for creating weak references.
  1111. Alternatively, when not using references, the
  1112. ``is_instance_valid(instance)`` can be used to check if an object has been
  1113. freed.
  1114. .. _doc_gdscript_signals:
  1115. Signals
  1116. ~~~~~~~
  1117. Signals are a tool to emit messages from an object that other objects can react
  1118. to. To create custom signals for a class, use the ``signal`` keyword.
  1119. ::
  1120. extends Node
  1121. # A signal named health_depleted.
  1122. signal health_depleted
  1123. .. note::
  1124. Signals are a `Callback
  1125. <https://en.wikipedia.org/wiki/Callback_(computer_programming)>`_
  1126. mechanism. They also fill the role of Observers, a common programming
  1127. pattern. For more information, read the `Observer tutorial
  1128. <https://gameprogrammingpatterns.com/observer.html>`_ in the
  1129. Game Programming Patterns ebook.
  1130. You can connect these signals to methods the same way you connect built-in
  1131. signals of nodes like :ref:`class_Button` or :ref:`class_RigidBody`.
  1132. In the example below, we connect the ``health_depleted`` signal from a
  1133. ``Character`` node to a ``Game`` node. When the ``Character`` node emits the
  1134. signal, the game node's ``_on_Character_health_depleted`` is called::
  1135. # Game.gd
  1136. func _ready():
  1137. var character_node = get_node('Character')
  1138. character_node.health_depleted.connect(_on_Character_health_depleted)
  1139. func _on_Character_health_depleted():
  1140. get_tree().reload_current_scene()
  1141. You can emit as many arguments as you want along with a signal.
  1142. Here is an example where this is useful. Let's say we want a life bar on screen
  1143. to react to health changes with an animation, but we want to keep the user
  1144. interface separate from the player in our scene tree.
  1145. In our ``Character.gd`` script, we define a ``health_changed`` signal and emit
  1146. it with :ref:`Signal.emit() <class_Signal_method_emit>`, and from
  1147. a ``Game`` node higher up our scene tree, we connect it to the ``Lifebar`` using
  1148. the :ref:`Signal.connect() <class_Signal_method_connect>` method::
  1149. # Character.gd
  1150. ...
  1151. signal health_changed
  1152. func take_damage(amount):
  1153. var old_health = health
  1154. health -= amount
  1155. # We emit the health_changed signal every time the
  1156. # character takes damage.
  1157. health_changed.emit(old_health, health)
  1158. ...
  1159. ::
  1160. # Lifebar.gd
  1161. # Here, we define a function to use as a callback when the
  1162. # character's health_changed signal is emitted.
  1163. ...
  1164. func _on_Character_health_changed(old_value, new_value):
  1165. if old_value > new_value:
  1166. progress_bar.modulate = Color.red
  1167. else:
  1168. progress_bar.modulate = Color.green
  1169. # Imagine that `animate` is a user-defined function that animates the
  1170. # bar filling up or emptying itself.
  1171. progress_bar.animate(old_value, new_value)
  1172. ...
  1173. In the ``Game`` node, we get both the ``Character`` and ``Lifebar`` nodes, then
  1174. connect the character, that emits the signal, to the receiver, the ``Lifebar``
  1175. node in this case.
  1176. ::
  1177. # Game.gd
  1178. func _ready():
  1179. var character_node = get_node('Character')
  1180. var lifebar_node = get_node('UserInterface/Lifebar')
  1181. character_node.health_changed.connect(lifebar_node._on_Character_health_changed)
  1182. This allows the ``Lifebar`` to react to health changes without coupling it to
  1183. the ``Character`` node.
  1184. You can write optional argument names in parentheses after the signal's
  1185. definition::
  1186. # Defining a signal that forwards two arguments.
  1187. signal health_changed(old_value, new_value)
  1188. These arguments show up in the editor's node dock, and Godot can use them to
  1189. generate callback functions for you. However, you can still emit any number of
  1190. arguments when you emit signals; it's up to you to emit the correct values.
  1191. .. image:: img/gdscript_basics_signals_node_tab_1.png
  1192. GDScript can bind an array of values to connections between a signal
  1193. and a method. When the signal is emitted, the callback method receives
  1194. the bound values. These bound arguments are unique to each connection,
  1195. and the values will stay the same.
  1196. You can use this array of values to add extra constant information to the
  1197. connection if the emitted signal itself doesn't give you access to all the data
  1198. that you need.
  1199. Building on the example above, let's say we want to display a log of the damage
  1200. taken by each character on the screen, like ``Player1 took 22 damage.``. The
  1201. ``health_changed`` signal doesn't give us the name of the character that took
  1202. damage. So when we connect the signal to the in-game console, we can add the
  1203. character's name in the binds array argument::
  1204. # Game.gd
  1205. func _ready():
  1206. var character_node = get_node('Character')
  1207. var battle_log_node = get_node('UserInterface/BattleLog')
  1208. character_node.health_changed.connect(battle_log_node._on_Character_health_changed, [character_node.name])
  1209. Our ``BattleLog`` node receives each element in the binds array as an extra argument::
  1210. # BattleLog.gd
  1211. func _on_Character_health_changed(old_value, new_value, character_name):
  1212. if not new_value <= old_value:
  1213. return
  1214. var damage = old_value - new_value
  1215. label.text += character_name + " took " + str(damage) + " damage."
  1216. Awaiting for signals
  1217. ~~~~~~~~~~~~~~~~~~~~
  1218. The ``await`` keyword can be used to create `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1219. which waits until a signal is emitted before continuing execution. Using the ``await`` keyword with a signal or a
  1220. call to a function that is also a coroutine will immediately return the control to the caller. When the signal is
  1221. emitted (or the called coroutine finishes), it will resume execution from the point on where it stopped.
  1222. For example, to stop execution until the user presses a button, you can do something like this::
  1223. func wait_confirmation():
  1224. print("Prompting user")
  1225. await $Button.button_up # Waits for the button_up signal from Button node.
  1226. print("User confirmed")
  1227. return true
  1228. In this case, the ``wait_confirmation`` becomes a coroutine, which means that the caller also needs to await for it::
  1229. func request_confirmation():
  1230. print("Will ask the user")
  1231. var confirmed = await wait_confirmation()
  1232. if confirmed:
  1233. print("User confirmed")
  1234. else:
  1235. print("User cancelled")
  1236. Note that requesting a coroutine's return value without ``await`` will trigger an error::
  1237. func wrong():
  1238. var confirmed = wait_confirmation() # Will give an error.
  1239. However, if you don't depend on the result, you can just call it asynchronously, which won't stop execution and won't
  1240. make the current function a coroutine::
  1241. func okay():
  1242. wait_confirmation()
  1243. print("This will be printed immediately, before the user press the button.")
  1244. If you use await with an expression that isn't a signal nor a coroutine, the value will be returned immediately and the
  1245. function won't give the control back to the caller::
  1246. func no_wait():
  1247. var x = await get_five()
  1248. print("This doesn't make this function a coroutine.")
  1249. func get_five():
  1250. return 5
  1251. This also means that returning a signal from a function that isn't a coroutine will make the caller await on that signal::
  1252. func get_signal():
  1253. return $Button.button_up
  1254. func wait_button():
  1255. await get_signal()
  1256. print("Button was pressed")
  1257. .. note:: Unlike ``yield`` in previous Godot versions, you cannot obtain the function state object. This in spirit of
  1258. type-safety, because a function cannot say that returns an ``int`` but actually give a function state object
  1259. during runtime.
  1260. Onready annotation
  1261. ~~~~~~~~~~~~~~~~~~
  1262. When using nodes, it's common to desire to keep references to parts
  1263. of the scene in a variable. As scenes are only warranted to be
  1264. configured when entering the active scene tree, the sub-nodes can only
  1265. be obtained when a call to ``Node._ready()`` is made.
  1266. ::
  1267. var my_label
  1268. func _ready():
  1269. my_label = get_node("MyLabel")
  1270. This can get a little cumbersome, especially when nodes and external
  1271. references pile up. For this, GDScript has the ``@onready`` annotation, that
  1272. defers initialization of a member variable until ``_ready()`` is called. It
  1273. can replace the above code with a single line::
  1274. @onready var my_label = get_node("MyLabel")
  1275. Assert keyword
  1276. ~~~~~~~~~~~~~~
  1277. The ``assert`` keyword can be used to check conditions in debug builds. These
  1278. assertions are ignored in non-debug builds. This means that the expression
  1279. passed as argument won't be evaluated in a project exported in release mode.
  1280. Due to this, assertions must **not** contain expressions that have
  1281. side effects. Otherwise, the behavior of the script would vary
  1282. depending on whether the project is run in a debug build.
  1283. ::
  1284. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  1285. assert(i == 0)
  1286. When running a project from the editor, the project will be paused if an
  1287. assertion error occurs.
  1288. You can optionally pass a custom error message to be shown if the assertion
  1289. fails::
  1290. assert(enemy_power < 256, "Enemy is too powerful!")