gdscript_basics.rst 72 KB

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