gdscript_styleguide.rst 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. .. _doc_gdscript_styleguide:
  2. GDScript style guide
  3. ====================
  4. This style guide lists conventions to write elegant GDScript. The goal is to
  5. encourage writing clean, readable code and promote consistency across projects,
  6. discussions, and tutorials. Hopefully, this will also support the development of
  7. auto-formatting tools.
  8. Since GDScript is close to Python, this guide is inspired by Python's
  9. `PEP 8 <https://www.python.org/dev/peps/pep-0008/>`__ programming
  10. style guide.
  11. Style guides aren't meant as hard rulebooks. At times, you may not be able to
  12. apply some of the guidelines below. When that happens, use your best judgment,
  13. and ask fellow developers for insights.
  14. In general, keeping your code consistent in your projects and within your team is
  15. more important than following this guide to a tee.
  16. .. note::
  17. Godot's built-in script editor uses a lot of these conventions
  18. by default. Let it help you.
  19. Here is a complete class example based on these guidelines:
  20. ::
  21. class_name StateMachine
  22. extends Node
  23. ## Hierarchical State machine for the player.
  24. ##
  25. ## Initializes states and delegates engine callbacks ([method Node._physics_process],
  26. ## [method Node._unhandled_input]) to the state.
  27. signal state_changed(previous, new)
  28. @export var initial_state: Node
  29. var is_active = true:
  30. set = set_is_active
  31. @onready var _state = initial_state:
  32. set = set_state
  33. @onready var _state_name = _state.name
  34. func _init():
  35. add_to_group("state_machine")
  36. func _enter_tree():
  37. print("this happens before the ready method!")
  38. func _ready():
  39. state_changed.connect(_on_state_changed)
  40. _state.enter()
  41. func _unhandled_input(event):
  42. _state.unhandled_input(event)
  43. func _physics_process(delta):
  44. _state.physics_process(delta)
  45. func transition_to(target_state_path, msg={}):
  46. if not has_node(target_state_path):
  47. return
  48. var target_state = get_node(target_state_path)
  49. assert(target_state.is_composite == false)
  50. _state.exit()
  51. self._state = target_state
  52. _state.enter(msg)
  53. Events.player_state_changed.emit(_state.name)
  54. func set_is_active(value):
  55. is_active = value
  56. set_physics_process(value)
  57. set_process_unhandled_input(value)
  58. set_block_signals(not value)
  59. func set_state(value):
  60. _state = value
  61. _state_name = _state.name
  62. func _on_state_changed(previous, new):
  63. print("state changed")
  64. state_changed.emit()
  65. class State:
  66. var foo = 0
  67. func _init():
  68. print("Hello!")
  69. .. _formatting:
  70. Formatting
  71. ----------
  72. Encoding and special characters
  73. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  74. * Use line feed (**LF**) characters to break lines, not CRLF or CR. *(editor default)*
  75. * Use one line feed character at the end of each file. *(editor default)*
  76. * Use **UTF-8** encoding without a `byte order mark <https://en.wikipedia.org/wiki/Byte_order_mark>`_. *(editor default)*
  77. * Use **Tabs** instead of spaces for indentation. *(editor default)*
  78. Indentation
  79. ~~~~~~~~~~~
  80. Each indent level should be one greater than the block containing it.
  81. **Good**:
  82. .. rst-class:: code-example-good
  83. ::
  84. for i in range(10):
  85. print("hello")
  86. **Bad**:
  87. .. rst-class:: code-example-bad
  88. ::
  89. for i in range(10):
  90. print("hello")
  91. for i in range(10):
  92. print("hello")
  93. Use 2 indent levels to distinguish continuation lines from
  94. regular code blocks.
  95. **Good**:
  96. .. rst-class:: code-example-good
  97. ::
  98. effect.interpolate_property(sprite, "transform/scale",
  99. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  100. Tween.TRANS_QUAD, Tween.EASE_OUT)
  101. **Bad**:
  102. .. rst-class:: code-example-bad
  103. ::
  104. effect.interpolate_property(sprite, "transform/scale",
  105. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  106. Tween.TRANS_QUAD, Tween.EASE_OUT)
  107. Exceptions to this rule are arrays, dictionaries, and enums. Use a single
  108. indentation level to distinguish continuation lines:
  109. **Good**:
  110. .. rst-class:: code-example-good
  111. ::
  112. var party = [
  113. "Godot",
  114. "Godette",
  115. "Steve",
  116. ]
  117. var character_dict = {
  118. "Name": "Bob",
  119. "Age": 27,
  120. "Job": "Mechanic",
  121. }
  122. enum Tiles {
  123. TILE_BRICK,
  124. TILE_FLOOR,
  125. TILE_SPIKE,
  126. TILE_TELEPORT,
  127. }
  128. **Bad**:
  129. .. rst-class:: code-example-bad
  130. ::
  131. var party = [
  132. "Godot",
  133. "Godette",
  134. "Steve",
  135. ]
  136. var character_dict = {
  137. "Name": "Bob",
  138. "Age": 27,
  139. "Job": "Mechanic",
  140. }
  141. enum Tiles {
  142. TILE_BRICK,
  143. TILE_FLOOR,
  144. TILE_SPIKE,
  145. TILE_TELEPORT,
  146. }
  147. Trailing comma
  148. ~~~~~~~~~~~~~~
  149. Use a trailing comma on the last line in arrays, dictionaries, and enums. This
  150. results in easier refactoring and better diffs in version control as the last
  151. line doesn't need to be modified when adding new elements.
  152. **Good**:
  153. .. rst-class:: code-example-good
  154. ::
  155. var array = [
  156. 1,
  157. 2,
  158. 3,
  159. ]
  160. **Bad**:
  161. .. rst-class:: code-example-bad
  162. ::
  163. var array = [
  164. 1,
  165. 2,
  166. 3
  167. ]
  168. Trailing commas are unnecessary in single-line lists, so don't add them in this case.
  169. **Good**:
  170. .. rst-class:: code-example-good
  171. ::
  172. var array = [1, 2, 3]
  173. **Bad**:
  174. .. rst-class:: code-example-bad
  175. ::
  176. var array = [1, 2, 3,]
  177. Blank lines
  178. ~~~~~~~~~~~
  179. Surround functions and class definitions with two blank lines:
  180. ::
  181. func heal(amount):
  182. health += amount
  183. health = min(health, max_health)
  184. health_changed.emit(health)
  185. func take_damage(amount, effect=null):
  186. health -= amount
  187. health = max(0, health)
  188. health_changed.emit(health)
  189. Use one blank line inside functions to separate logical sections.
  190. .. note::
  191. We use a single line between classes and function definitions in the class reference and
  192. in short code snippets in this documentation.
  193. Line length
  194. ~~~~~~~~~~~
  195. Keep individual lines of code under 100 characters.
  196. If you can, try to keep lines under 80 characters. This helps to read the code
  197. on small displays and with two scripts opened side-by-side in an external text
  198. editor. For example, when looking at a differential revision.
  199. One statement per line
  200. ~~~~~~~~~~~~~~~~~~~~~~
  201. Avoid combining multiple statements on a single line, including conditional
  202. statements, to adhere to the GDScript style guidelines for readability.
  203. **Good**:
  204. .. rst-class:: code-example-good
  205. ::
  206. if position.x > width:
  207. position.x = 0
  208. if flag:
  209. print("flagged")
  210. **Bad**:
  211. .. rst-class:: code-example-bad
  212. ::
  213. if position.x > width: position.x = 0
  214. if flag: print("flagged")
  215. The only exception to that rule is the ternary operator:
  216. ::
  217. next_state = "idle" if is_on_floor() else "fall"
  218. Format multiline statements for readability
  219. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  220. When you have particularly long ``if`` statements or nested ternary expressions,
  221. wrapping them over multiple lines improves readability. Since continuation lines
  222. are still part of the same expression, 2 indent levels should be used instead of one.
  223. GDScript allows wrapping statements using multiple lines using parentheses or
  224. backslashes. Parentheses are favored in this style guide since they make for
  225. easier refactoring. With backslashes, you have to ensure that the last line
  226. never contains a backslash at the end. With parentheses, you don't have to
  227. worry about the last line having a backslash at the end.
  228. When wrapping a conditional expression over multiple lines, the ``and``/``or``
  229. keywords should be placed at the beginning of the line continuation, not at the
  230. end of the previous line.
  231. **Good**:
  232. .. rst-class:: code-example-good
  233. ::
  234. var angle_degrees = 135
  235. var quadrant = (
  236. "northeast" if angle_degrees <= 90
  237. else "southeast" if angle_degrees <= 180
  238. else "southwest" if angle_degrees <= 270
  239. else "northwest"
  240. )
  241. var position = Vector2(250, 350)
  242. if (
  243. position.x > 200 and position.x < 400
  244. and position.y > 300 and position.y < 400
  245. ):
  246. pass
  247. **Bad**:
  248. .. rst-class:: code-example-bad
  249. ::
  250. var angle_degrees = 135
  251. var quadrant = "northeast" if angle_degrees <= 90 else "southeast" if angle_degrees <= 180 else "southwest" if angle_degrees <= 270 else "northwest"
  252. var position = Vector2(250, 350)
  253. if position.x > 200 and position.x < 400 and position.y > 300 and position.y < 400:
  254. pass
  255. Avoid unnecessary parentheses
  256. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  257. Avoid parentheses in expressions and conditional statements. Unless
  258. necessary for order of operations or wrapping over multiple lines,
  259. they only reduce readability.
  260. **Good**:
  261. .. rst-class:: code-example-good
  262. ::
  263. if is_colliding():
  264. queue_free()
  265. **Bad**:
  266. .. rst-class:: code-example-bad
  267. ::
  268. if (is_colliding()):
  269. queue_free()
  270. .. _boolean_operators:
  271. Boolean operators
  272. ~~~~~~~~~~~~~~~~~
  273. Prefer the plain English versions of boolean operators, as they are the most accessible:
  274. - Use ``and`` instead of ``&&``.
  275. - Use ``or`` instead of ``||``.
  276. - Use ``not`` instead of ``!``.
  277. You may also use parentheses around boolean operators to clear any ambiguity.
  278. This can make long expressions easier to read.
  279. **Good**:
  280. .. rst-class:: code-example-good
  281. ::
  282. if (foo and bar) or not baz:
  283. print("condition is true")
  284. **Bad**:
  285. .. rst-class:: code-example-bad
  286. ::
  287. if foo && bar || !baz:
  288. print("condition is true")
  289. Comment spacing
  290. ~~~~~~~~~~~~~~~
  291. Regular comments (``#``) and documentation comments (``##``) should start with a
  292. space, but not code that you comment out. Additionally, code region comments
  293. (``#region``/``#endregion``) must follow that precise syntax, so they should not
  294. start with a space.
  295. Using a space for regular and documentation comments helps differentiate text
  296. comments from disabled code.
  297. **Good**:
  298. .. rst-class:: code-example-good
  299. ::
  300. # This is a comment.
  301. #print("This is disabled code")
  302. **Bad**:
  303. .. rst-class:: code-example-bad
  304. ::
  305. #This is a comment.
  306. # print("This is disabled code")
  307. .. note::
  308. In the script editor, to toggle commenting of the selected code, press
  309. :kbd:`Ctrl + K`. This feature adds/removes a single ``#`` sign before any
  310. code on the selected lines.
  311. Whitespace
  312. ~~~~~~~~~~
  313. Always use one space around operators and after commas. Also, avoid extra spaces
  314. in dictionary references and function calls. One exception to this is for
  315. single-line dictionary declarations, where a space should be added after the
  316. opening brace and before the closing brace. This makes the dictionary easier to
  317. visually distinguish from an array, as the ``[]`` characters look close to
  318. ``{}`` with most fonts.
  319. **Good**:
  320. .. rst-class:: code-example-good
  321. ::
  322. position.x = 5
  323. position.y = target_position.y + 10
  324. dict["key"] = 5
  325. my_array = [4, 5, 6]
  326. my_dictionary = { key = "value" }
  327. print("foo")
  328. **Bad**:
  329. .. rst-class:: code-example-bad
  330. ::
  331. position.x=5
  332. position.y = mpos.y+10
  333. dict ["key"] = 5
  334. myarray = [4,5,6]
  335. my_dictionary = {key = "value"}
  336. print ("foo")
  337. Don't use spaces to align expressions vertically:
  338. ::
  339. x = 100
  340. y = 100
  341. velocity = 500
  342. Quotes
  343. ~~~~~~
  344. Use double quotes unless single quotes make it possible to escape fewer
  345. characters in a given string. See the examples below:
  346. ::
  347. # Normal string.
  348. print("hello world")
  349. # Use double quotes as usual to avoid escapes.
  350. print("hello 'world'")
  351. # Use single quotes as an exception to the rule to avoid escapes.
  352. print('hello "world"')
  353. # Both quote styles would require 2 escapes; prefer double quotes if it's a tie.
  354. print("'hello' \"world\"")
  355. Numbers
  356. ~~~~~~~
  357. Don't omit the leading or trailing zero in floating-point numbers. Otherwise,
  358. this makes them less readable and harder to distinguish from integers at a
  359. glance.
  360. **Good**:
  361. .. rst-class:: code-example-good
  362. ::
  363. var float_number = 0.234
  364. var other_float_number = 13.0
  365. **Bad**:
  366. .. rst-class:: code-example-bad
  367. ::
  368. var float_number = .234
  369. var other_float_number = 13.
  370. Use lowercase for letters in hexadecimal numbers, as their lower height makes
  371. the number easier to read.
  372. **Good**:
  373. .. rst-class:: code-example-good
  374. ::
  375. var hex_number = 0xfb8c0b
  376. **Bad**:
  377. .. rst-class:: code-example-bad
  378. ::
  379. var hex_number = 0xFB8C0B
  380. Take advantage of GDScript's underscores in literals to make large numbers more
  381. readable.
  382. **Good**:
  383. .. rst-class:: code-example-good
  384. ::
  385. var large_number = 1_234_567_890
  386. var large_hex_number = 0xffff_f8f8_0000
  387. var large_bin_number = 0b1101_0010_1010
  388. # Numbers lower than 1000000 generally don't need separators.
  389. var small_number = 12345
  390. **Bad**:
  391. .. rst-class:: code-example-bad
  392. ::
  393. var large_number = 1234567890
  394. var large_hex_number = 0xfffff8f80000
  395. var large_bin_number = 0b110100101010
  396. # Numbers lower than 1000000 generally don't need separators.
  397. var small_number = 12_345
  398. .. _naming_conventions:
  399. Naming conventions
  400. ------------------
  401. These naming conventions follow the Godot Engine style. Breaking these will make
  402. your code clash with the built-in naming conventions, leading to inconsistent
  403. code. As a summary table:
  404. +---------------+----------------+----------------------------------------------------+
  405. | Type | Convention | Example |
  406. +===============+================+====================================================+
  407. | File names | snake_case | ``yaml_parser.gd`` |
  408. +---------------+----------------+----------------------------------------------------+
  409. | Class names | PascalCase | ``class_name YAMLParser`` |
  410. +---------------+----------------+----------------------------------------------------+
  411. | Node names | PascalCase | ``Camera3D``, ``Player`` |
  412. +---------------+----------------+----------------------------------------------------+
  413. | Functions | snake_case | ``func load_level():`` |
  414. +---------------+----------------+----------------------------------------------------+
  415. | Variables | snake_case | ``var particle_effect`` |
  416. +---------------+----------------+----------------------------------------------------+
  417. | Signals | snake_case | ``signal door_opened`` |
  418. +---------------+----------------+----------------------------------------------------+
  419. | Constants | CONSTANT_CASE | ``const MAX_SPEED = 200`` |
  420. +---------------+----------------+----------------------------------------------------+
  421. | Enum names | PascalCase | ``enum Element`` |
  422. +---------------+----------------+----------------------------------------------------+
  423. | Enum members | CONSTANT_CASE | ``{EARTH, WATER, AIR, FIRE}`` |
  424. +---------------+----------------+----------------------------------------------------+
  425. File names
  426. ~~~~~~~~~~
  427. Use snake_case for file names. For named classes, convert the PascalCase class
  428. name to snake_case::
  429. # This file should be saved as `weapon.gd`.
  430. class_name Weapon
  431. extends Node
  432. ::
  433. # This file should be saved as `yaml_parser.gd`.
  434. class_name YAMLParser
  435. extends Object
  436. This is consistent with how C++ files are named in Godot's source code. This
  437. also avoids case sensitivity issues that can crop up when exporting a project
  438. from Windows to other platforms.
  439. Classes and nodes
  440. ~~~~~~~~~~~~~~~~~
  441. Use PascalCase for class and node names:
  442. ::
  443. extends CharacterBody3D
  444. Also use PascalCase when loading a class into a constant or a variable:
  445. ::
  446. const Weapon = preload("res://weapon.gd")
  447. Functions and variables
  448. ~~~~~~~~~~~~~~~~~~~~~~~
  449. Use snake\_case to name functions and variables:
  450. ::
  451. var particle_effect
  452. func load_level():
  453. Prepend a single underscore (\_) to virtual methods functions the user must
  454. override, private functions, and private variables:
  455. ::
  456. var _counter = 0
  457. func _recalculate_path():
  458. Signals
  459. ~~~~~~~
  460. Use the past tense to name signals:
  461. ::
  462. signal door_opened
  463. signal score_changed
  464. Constants and enums
  465. ~~~~~~~~~~~~~~~~~~~
  466. Write constants with CONSTANT\_CASE, that is to say in all caps with an
  467. underscore (\_) to separate words:
  468. ::
  469. const MAX_SPEED = 200
  470. Use PascalCase for enum *names* and CONSTANT\_CASE for their members, as they
  471. are constants:
  472. ::
  473. enum Element {
  474. EARTH,
  475. WATER,
  476. AIR,
  477. FIRE,
  478. }
  479. Write enums with each item on its own line. This allows adding documentation comments above each item
  480. more easily, and also makes for cleaner diffs in version control when items are added or removed.
  481. **Good**:
  482. .. rst-class:: code-example-good
  483. ::
  484. enum Element {
  485. EARTH,
  486. WATER,
  487. AIR,
  488. FIRE,
  489. }
  490. **Bad**:
  491. .. rst-class:: code-example-bad
  492. ::
  493. enum Element { EARTH, WATER, AIR, FIRE }
  494. Code order
  495. ----------
  496. This section focuses on code order. For formatting, see
  497. :ref:`formatting`. For naming conventions, see :ref:`naming_conventions`.
  498. We suggest to organize GDScript code this way:
  499. ::
  500. 01. @tool
  501. 02. class_name
  502. 03. extends
  503. 04. ## docstring
  504. 05. signals
  505. 06. enums
  506. 07. constants
  507. 08. @export variables
  508. 09. public variables
  509. 10. private variables
  510. 11. @onready variables
  511. 12. optional built-in virtual _init method
  512. 13. optional built-in virtual _enter_tree() method
  513. 14. built-in virtual _ready method
  514. 15. remaining built-in virtual methods
  515. 16. public methods
  516. 17. private methods
  517. 18. subclasses
  518. We optimized the order to make it easy to read the code from top to bottom, to
  519. help developers reading the code for the first time understand how it works, and
  520. to avoid errors linked to the order of variable declarations.
  521. This code order follows four rules of thumb:
  522. 1. Properties and signals come first, followed by methods.
  523. 2. Public comes before private.
  524. 3. Virtual callbacks come before the class's interface.
  525. 4. The object's construction and initialization functions, ``_init`` and
  526. ``_ready``, come before functions that modify the object at runtime.
  527. Class declaration
  528. ~~~~~~~~~~~~~~~~~
  529. If the code is meant to run in the editor, place the ``@tool`` annotation on the
  530. first line of the script.
  531. Follow with the ``class_name`` if necessary. You can turn a GDScript file into a
  532. global type in your project using this feature. For more information, see
  533. :ref:`doc_gdscript`.
  534. Then, add the ``extends`` keyword if the class extends a built-in type.
  535. Following that, you should have the class's optional
  536. :ref:`documentation comments <doc_gdscript_documentation_comments>`.
  537. You can use that to explain the role of your class to your teammates, how it works,
  538. and how other developers should use it, for example.
  539. ::
  540. class_name MyNode
  541. extends Node
  542. ## A brief description of the class's role and functionality.
  543. ##
  544. ## The description of the script, what it can do,
  545. ## and any further detail.
  546. Signals and properties
  547. ~~~~~~~~~~~~~~~~~~~~~~
  548. Write signal declarations, followed by properties, that is to say, member
  549. variables, after the docstring.
  550. Enums should come after signals, as you can use them as export hints for other
  551. properties.
  552. Then, write constants, exported variables, public, private, and onready
  553. variables, in that order.
  554. ::
  555. signal player_spawned(position)
  556. enum Jobs {
  557. KNIGHT,
  558. WIZARD,
  559. ROGUE,
  560. HEALER,
  561. SHAMAN,
  562. }
  563. const MAX_LIVES = 3
  564. @export var job: Jobs = Jobs.KNIGHT
  565. @export var max_health = 50
  566. @export var attack = 5
  567. var health = max_health:
  568. set(new_health):
  569. health = new_health
  570. var _speed = 300.0
  571. @onready var sword = get_node("Sword")
  572. @onready var gun = get_node("Gun")
  573. .. note::
  574. GDScript evaluates ``@onready`` variables right before the ``_ready``
  575. callback. You can use that to cache node dependencies, that is to say, to get
  576. child nodes in the scene that your class relies on. This is what the example
  577. above shows.
  578. Member variables
  579. ~~~~~~~~~~~~~~~~
  580. Don't declare member variables if they are only used locally in a method, as it
  581. makes the code more difficult to follow. Instead, declare them as local
  582. variables in the method's body.
  583. Local variables
  584. ~~~~~~~~~~~~~~~
  585. Declare local variables as close as possible to their first use. This makes it
  586. easier to follow the code, without having to scroll too much to find where the
  587. variable was declared.
  588. Methods and static functions
  589. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  590. After the class's properties come the methods.
  591. Start with the ``_init()`` callback method, that the engine will call upon
  592. creating the object in memory. Follow with the ``_ready()`` callback, that Godot
  593. calls when it adds a node to the scene tree.
  594. These functions should come first because they show how the object is
  595. initialized.
  596. Other built-in virtual callbacks, like ``_unhandled_input()`` and
  597. ``_physics_process``, should come next. These control the object's main loop and
  598. interactions with the game engine.
  599. The rest of the class's interface, public and private methods, come after that,
  600. in that order.
  601. ::
  602. func _init():
  603. add_to_group("state_machine")
  604. func _ready():
  605. state_changed.connect(_on_state_changed)
  606. _state.enter()
  607. func _unhandled_input(event):
  608. _state.unhandled_input(event)
  609. func transition_to(target_state_path, msg={}):
  610. if not has_node(target_state_path):
  611. return
  612. var target_state = get_node(target_state_path)
  613. assert(target_state.is_composite == false)
  614. _state.exit()
  615. self._state = target_state
  616. _state.enter(msg)
  617. Events.player_state_changed.emit(_state.name)
  618. func _on_state_changed(previous, new):
  619. print("state changed")
  620. state_changed.emit()
  621. Static typing
  622. -------------
  623. GDScript supports :ref:`optional static typing<doc_gdscript_static_typing>`.
  624. Declared types
  625. ~~~~~~~~~~~~~~
  626. To declare a variable's type, use ``<variable>: <type>``:
  627. ::
  628. var health: int = 0
  629. To declare the return type of a function, use ``-> <type>``:
  630. ::
  631. func heal(amount: int) -> void:
  632. Inferred types
  633. ~~~~~~~~~~~~~~
  634. In most cases you can let the compiler infer the type, using ``:=``.
  635. Prefer ``:=`` when the type is written on the same line as the assignment,
  636. otherwise prefer writing the type explicitly.
  637. **Good**:
  638. .. rst-class:: code-example-good
  639. ::
  640. var health: int = 0 # The type can be int or float, and thus should be stated explicitly.
  641. var direction := Vector3(1, 2, 3) # The type is clearly inferred as Vector3.
  642. Include the type hint when the type is ambiguous, and
  643. omit the type hint when it's redundant.
  644. **Bad**:
  645. .. rst-class:: code-example-bad
  646. ::
  647. var health := 0 # Typed as int, but it could be that float was intended.
  648. var direction: Vector3 = Vector3(1, 2, 3) # The type hint has redundant information.
  649. # What type is this? It's not immediately clear to the reader, so it's bad.
  650. var value := complex_function()
  651. In some cases, the type must be stated explicitly, otherwise the behavior
  652. will not be as expected because the compiler will only be able to use
  653. the function's return type. For example, ``get_node()`` cannot infer a type
  654. unless the scene or file of the node is loaded in memory. In this case, you
  655. should set the type explicitly.
  656. **Good**:
  657. .. rst-class:: code-example-good
  658. ::
  659. @onready var health_bar: ProgressBar = get_node("UI/LifeBar")
  660. Alternatively, you can use the ``as`` keyword to cast the return type, and
  661. that type will be used to infer the type of the var.
  662. .. rst-class:: code-example-good
  663. ::
  664. @onready var health_bar := get_node("UI/LifeBar") as ProgressBar
  665. # health_bar will be typed as ProgressBar
  666. This option is also considered more :ref:`type-safe<doc_gdscript_static_typing_safe_lines>` than the first.
  667. **Bad**:
  668. .. rst-class:: code-example-bad
  669. ::
  670. # The compiler can't infer the exact type and will use Node
  671. # instead of ProgressBar.
  672. @onready var health_bar := get_node("UI/LifeBar")