running_code_in_the_editor.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. .. _doc_running_code_in_the_editor:
  2. Running code in the editor
  3. ==========================
  4. What is ``@tool``?
  5. ------------------
  6. ``@tool`` is a powerful line of code that, when added at the top of your script,
  7. makes it execute in the editor. You can also decide which parts of the script
  8. execute in the editor, which in game, and which in both.
  9. You can use it for doing many things, but it is mostly useful in level design
  10. for visually presenting things that are hard to predict ourselves. Here are some
  11. use cases:
  12. - If you have a cannon that shoots cannonballs affected by physics (gravity),
  13. you can draw the cannonball's trajectory in the editor, making level design a
  14. lot easier.
  15. - If you have jumppads with varying jump heights, you can draw the maximum jump
  16. height a player would reach if it jumped on one, also making level design
  17. easier.
  18. - If your player doesn't use a sprite, but draws itself using code, you can make
  19. that drawing code execute in the editor to see your player.
  20. .. danger::
  21. ``@tool`` scripts run inside the editor, and let you access the scene tree
  22. of the currently edited scene. This is a powerful feature which also comes
  23. with caveats, as the editor does not include protections for potential
  24. misuse of ``@tool`` scripts.
  25. Be **extremely** cautious when manipulating the scene tree, especially via
  26. :ref:`Node.queue_free<class_Node_method_queue_free>`, as it can cause
  27. crashes if you free a node while the editor runs logic involving it.
  28. How to use ``@tool``
  29. --------------------
  30. To turn a script into a tool, add the ``@tool`` annotation at the top of your code.
  31. To check if you are currently in the editor, use: ``Engine.is_editor_hint()``.
  32. For example, if you want to execute some code only in the editor, use:
  33. .. tabs::
  34. .. code-tab:: gdscript GDScript
  35. if Engine.is_editor_hint():
  36. # Code to execute when in editor.
  37. .. code-tab:: csharp
  38. if (Engine.IsEditorHint())
  39. {
  40. // Code to execute when in editor.
  41. }
  42. On the other hand, if you want to execute code only in game, simply negate the
  43. same statement:
  44. .. tabs::
  45. .. code-tab:: gdscript GDScript
  46. if not Engine.is_editor_hint():
  47. # Code to execute when in game.
  48. .. code-tab:: csharp
  49. if (!Engine.IsEditorHint())
  50. {
  51. // Code to execute when in game.
  52. }
  53. Pieces of code that do not have either of the 2 conditions above will run both
  54. in-editor and in-game.
  55. Here is how a ``_process()`` function might look for you:
  56. .. tabs::
  57. .. code-tab:: gdscript GDScript
  58. func _process(delta):
  59. if Engine.is_editor_hint():
  60. # Code to execute in editor.
  61. if not Engine.is_editor_hint():
  62. # Code to execute in game.
  63. # Code to execute both in editor and in game.
  64. .. code-tab:: csharp
  65. public override void _Process(double delta)
  66. {
  67. if (Engine.IsEditorHint())
  68. {
  69. // Code to execute in editor.
  70. }
  71. if (!Engine.IsEditorHint())
  72. {
  73. // Code to execute in game.
  74. }
  75. // Code to execute both in editor and in game.
  76. }
  77. .. _doc_running_code_in_the_editor_important_information:
  78. Important information
  79. ---------------------
  80. The general rule is that **any other GDScript that your tool script uses must
  81. *also* be a tool**. The editor is not able to construct instances from GDScript
  82. files without ``@tool``, which means you cannot call methods or reference member
  83. variables from them otherwise. However, since static methods, constants and
  84. enums can be used without creating an instance, it is possible to call them or
  85. reference them from a ``@tool`` script onto other non-tool scripts. One exception to
  86. this are :ref:`static variables <doc_gdscript_basics_static_variables>`.
  87. If you try to read a static variable's value in a script that does not have
  88. ``@tool``, it will always return ``null`` but won't print a warning or error
  89. when doing so. This restriction does not apply to static methods, which can be
  90. called regardless of whether the target script is in tool mode.
  91. Extending a ``@tool`` script does not automatically make the extending script
  92. a ``@tool``. Omitting ``@tool`` from the extending script will disable tool
  93. behavior from the super class. Therefore, the extending script should also
  94. specify the ``@tool`` annotation.
  95. Modifications in the editor are permanent, with no undo/redo possible. For
  96. example, in the next section when we remove the script, the node will keep its
  97. rotation. Be careful to avoid making unwanted modifications. Consider setting up
  98. :ref:`version control <doc_version_control_systems>` to avoid losing work in
  99. case you make a mistake.
  100. Using the debugger and breakpoints on tool scripts is not currently supported.
  101. Breakpoints placed in the script editor or using the ``breakpoint`` keyword are
  102. ignored. You can use print statements to display the contents of variables
  103. instead.
  104. Try ``@tool`` out
  105. -----------------
  106. Add a ``Sprite2D`` node to your scene and set the texture to Godot icon. Attach
  107. and open a script, and change it to this:
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. @tool
  111. extends Sprite2D
  112. func _process(delta):
  113. rotation += PI * delta
  114. .. code-tab:: csharp
  115. using Godot;
  116. [Tool]
  117. public partial class MySprite : Sprite2D
  118. {
  119. public override void _Process(double delta)
  120. {
  121. Rotation += Mathf.Pi * (float)delta;
  122. }
  123. }
  124. Save the script and return to the editor. You should now see your object rotate.
  125. If you run the game, it will also rotate.
  126. .. warning::
  127. You may need to restart the editor. This is a known bug found in all Godot 4 versions:
  128. `GH-66381 <https://github.com/godotengine/godot/issues/66381>`_.
  129. .. image:: img/rotating_in_editor.gif
  130. .. note::
  131. If you don't see the changes, reload the scene (close it and open it again).
  132. Now let's choose which code runs when. Modify your ``_process()`` function to
  133. look like this:
  134. .. tabs::
  135. .. code-tab:: gdscript GDScript
  136. func _process(delta):
  137. if Engine.is_editor_hint():
  138. rotation += PI * delta
  139. else:
  140. rotation -= PI * delta
  141. .. code-tab:: csharp
  142. public override void _Process(double delta)
  143. {
  144. if (Engine.IsEditorHint())
  145. {
  146. Rotation += Mathf.Pi * (float)delta;
  147. }
  148. else
  149. {
  150. Rotation -= Mathf.Pi * (float)delta;
  151. }
  152. }
  153. Save the script. Now the object will spin clockwise in the editor, but if you
  154. run the game, it will spin counter-clockwise.
  155. Editing variables
  156. -----------------
  157. Add and export a variable speed to the script. To update the speed and also reset the rotation
  158. angle add a setter ``set(new_speed)`` which is executed with the input from the inspector. Modify
  159. ``_process()`` to include the rotation speed.
  160. .. tabs::
  161. .. code-tab:: gdscript GDScript
  162. @tool
  163. extends Sprite2D
  164. @export var speed = 1:
  165. # Update speed and reset the rotation.
  166. set(new_speed):
  167. speed = new_speed
  168. rotation = 0
  169. func _process(delta):
  170. rotation += PI * delta * speed
  171. .. code-tab:: csharp
  172. using Godot;
  173. [Tool]
  174. public partial class MySprite : Sprite2D
  175. {
  176. private float _speed = 1;
  177. [Export]
  178. public float Speed
  179. {
  180. get => _speed;
  181. set
  182. {
  183. // Update speed and reset the rotation.
  184. _speed = value;
  185. Rotation = 0;
  186. }
  187. }
  188. public override void _Process(double delta)
  189. {
  190. Rotation += Mathf.Pi * (float)delta * _speed;
  191. }
  192. }
  193. .. note::
  194. Code from other nodes doesn't run in the editor. Your access to other nodes
  195. is limited. You can access the tree and nodes, and their default properties,
  196. but you can't access user variables. If you want to do so, other nodes have
  197. to run in the editor too.
  198. Getting notified when resources change
  199. --------------------------------------
  200. Sometimes you want your tool to use a resource. However, when you change a
  201. property of that resource in the editor, the ``set()`` method of your tool will
  202. not be called.
  203. .. tabs::
  204. .. code-tab:: gdscript GDScript
  205. @tool
  206. class_name MyTool
  207. extends Node
  208. @export var resource: MyResource:
  209. set(new_resource):
  210. resource = new_resource
  211. _on_resource_set()
  212. # This will only be called when you create, delete, or paste a resource.
  213. # You will not get an update when tweaking properties of it.
  214. func _on_resource_set():
  215. print("My resource was set!")
  216. .. code-tab:: csharp
  217. using Godot;
  218. [Tool]
  219. public partial class MyTool : Node
  220. {
  221. private MyResource _resource;
  222. [Export]
  223. public MyResource Resource
  224. {
  225. get => _resource;
  226. set
  227. {
  228. _resource = value;
  229. OnResourceSet();
  230. }
  231. }
  232. }
  233. // This will only be called when you create, delete, or paste a resource.
  234. // You will not get an update when tweaking properties of it.
  235. private void OnResourceSet()
  236. {
  237. GD.Print("My resource was set!");
  238. }
  239. To get around this problem you first have to make your resource a tool and make it
  240. emit the ``changed`` signal whenever a property is set:
  241. .. tabs::
  242. .. code-tab:: gdscript GDScript
  243. # Make Your Resource a tool.
  244. @tool
  245. class_name MyResource
  246. extends Resource
  247. @export var property = 1:
  248. set(new_setting):
  249. property = new_setting
  250. # Emit a signal when the property is changed.
  251. changed.emit()
  252. .. code-tab:: csharp
  253. using Godot;
  254. [Tool]
  255. public partial class MyResource : Resource
  256. {
  257. private float _property = 1;
  258. [Export]
  259. public float Property
  260. {
  261. get => _property;
  262. set
  263. {
  264. _property = value;
  265. // Emit a signal when the property is changed.
  266. EmitChanged();
  267. }
  268. }
  269. }
  270. You then want to connect the signal when a new resource is set:
  271. .. tabs::
  272. .. code-tab:: gdscript GDScript
  273. @tool
  274. class_name MyTool
  275. extends Node
  276. @export var resource: MyResource:
  277. set(new_resource):
  278. resource = new_resource
  279. # Connect the changed signal as soon as a new resource is being added.
  280. resource.changed.connect(_on_resource_changed)
  281. func _on_resource_changed():
  282. print("My resource just changed!")
  283. .. code-tab:: csharp
  284. using Godot;
  285. [Tool]
  286. public partial class MyTool : Node
  287. {
  288. private MyResource _resource;
  289. [Export]
  290. public MyResource Resource
  291. {
  292. get => _resource;
  293. set
  294. {
  295. _resource = value;
  296. // Connect the changed signal as soon as a new resource is being added.
  297. _resource.Changed += OnResourceChanged;
  298. }
  299. }
  300. }
  301. private void OnResourceChanged()
  302. {
  303. GD.Print("My resource just changed!");
  304. }
  305. Lastly, remember to disconnect the signal as the old resource being used and changed somewhere else
  306. would cause unneeded updates.
  307. .. tabs::
  308. .. code-tab:: gdscript GDScript
  309. @export var resource: MyResource:
  310. set(new_resource):
  311. # Disconnect the signal if the previous resource was not null.
  312. if resource != null:
  313. resource.changed.disconnect(_on_resource_changed)
  314. resource = new_resource
  315. resource.changed.connect(_on_resource_changed)
  316. .. code-tab:: csharp
  317. [Export]
  318. public MyResource Resource
  319. {
  320. get => _resource;
  321. set
  322. {
  323. // Disconnect the signal if the previous resource was not null.
  324. if (_resource != null)
  325. {
  326. _resource.Changed -= OnResourceChanged;
  327. }
  328. _resource = value;
  329. _resource.Changed += OnResourceChanged;
  330. }
  331. }
  332. Reporting node configuration warnings
  333. -------------------------------------
  334. Godot uses a *node configuration warning* system to warn users about incorrectly
  335. configured nodes. When a node isn't configured correctly, a yellow warning sign
  336. appears next to the node's name in the Scene dock. When you hover or click on
  337. the icon, a warning message pops up. You can use this feature in your scripts to
  338. help you and your team avoid mistakes when setting up scenes.
  339. When using node configuration warnings, when any value that should affect or
  340. remove the warning changes, you need to call
  341. :ref:`update_configuration_warnings<class_Node_method_update_configuration_warnings>` .
  342. By default, the warning only updates when closing and reopening the scene.
  343. .. tabs::
  344. .. code-tab:: gdscript GDScript
  345. # Use setters to update the configuration warning automatically.
  346. @export var title = "":
  347. set(p_title):
  348. if p_title != title:
  349. title = p_title
  350. update_configuration_warnings()
  351. @export var description = "":
  352. set(p_description):
  353. if p_description != description:
  354. description = p_description
  355. update_configuration_warnings()
  356. func _get_configuration_warnings():
  357. var warnings = []
  358. if title == "":
  359. warnings.append("Please set `title` to a non-empty value.")
  360. if description.length() >= 100:
  361. warnings.append("`description` should be less than 100 characters long.")
  362. # Returning an empty array means "no warning".
  363. return warnings
  364. .. _doc_running_code_in_the_editor_editorscript:
  365. Running one-off scripts using EditorScript
  366. ------------------------------------------
  367. Sometimes, you need to run code just one time to automate a certain task that is
  368. not available in the editor out of the box. Some examples might be:
  369. - Use as a playground for GDScript or C# scripting without having to run a project.
  370. ``print()`` output is displayed in the editor Output panel.
  371. - Scale all light nodes in the currently edited scene, as you noticed your level
  372. ends up looking too dark or too bright after placing lights where desired.
  373. - Replace nodes that were copy-pasted with scene instances to make them easier
  374. to modify later.
  375. This is available in Godot by extending :ref:`class_EditorScript` in a script.
  376. This provides a way to run individual scripts in the editor without having to
  377. create an editor plugin.
  378. To create an EditorScript, right-click a folder or empty space in the FileSystem
  379. dock then choose **New > Script...**. In the script creation dialog, click the
  380. tree icon to choose an object to extend from (or enter ``EditorScript`` directly
  381. in the field on the left, though note this is case-sensitive):
  382. .. figure:: img/running_code_in_the_editor_creating_editor_script.webp
  383. :align: center
  384. :alt: Creating an editor script in the script editor creation dialog
  385. Creating an editor script in the script editor creation dialog
  386. This will automatically select a script template that is suited for
  387. EditorScripts, with a ``_run()`` method already inserted:
  388. ::
  389. @tool
  390. extends EditorScript
  391. # Called when the script is executed (using File -> Run in Script Editor).
  392. func _run():
  393. pass
  394. This ``_run()`` method is executed when you use **File > Run** or the keyboard
  395. shortcut :kbd:`Ctrl + Shift + X` while the EditorScript is the currently open
  396. script in the script editor. This keyboard shortcut is only effective when
  397. currently focused on the script editor.
  398. Scripts that extend EditorScript must be ``@tool`` scripts to function.
  399. .. note::
  400. EditorScripts can only be run from the Godot script editor. If you are using
  401. an external editor, open the script inside the Godot script editor to run it.
  402. .. danger::
  403. EditorScripts have no undo/redo functionality, so **make sure to save your
  404. scene before running one** if the script is designed to modify any data.
  405. To access nodes in the currently edited scene, use the
  406. :ref:`EditorScript.get_scene <class_EditorScript_method_get_scene>` method which
  407. returns the root Node of the currently edited scene. Here's an example that
  408. recursively gets all nodes in the currently edited scene and doubles the range
  409. of all OmniLight3D nodes:
  410. ::
  411. @tool
  412. extends EditorScript
  413. func _run():
  414. for node in get_all_children(get_scene()):
  415. if node is OmniLight3D:
  416. # Don't operate on instanced subscene children, as changes are lost
  417. # when reloading the scene.
  418. # See the "Instancing scenes" section below for a description of `owner`.
  419. var is_instanced_subscene_child = node != get_scene() and node.owner != get_scene()
  420. if not is_instanced_subscene_child:
  421. node.omni_range *= 2.0
  422. # This function is recursive: it calls itself to get lower levels of child nodes as needed.
  423. # `children_acc` is the accumulator parameter that allows this function to work.
  424. # It should be left to its default value when you call this function directly.
  425. func get_all_children(in_node, children_acc = []):
  426. children_acc.push_back(in_node)
  427. for child in in_node.get_children():
  428. children_acc = get_all_children(child, children_acc)
  429. return children_acc
  430. .. tip::
  431. You can change the currently edited scene at the top of the editor even
  432. while the Script view is open. This will affect the return value of
  433. :ref:`EditorScript.get_scene <class_EditorScript_method_get_scene>`, so make
  434. sure you've selected the scene you intend to iterate upon before running
  435. the script.
  436. Instancing scenes
  437. -----------------
  438. You can instantiate packed scenes normally and add them to the scene currently
  439. opened in the editor. By default, nodes or scenes added with
  440. :ref:`Node.add_child(node) <class_Node_method_add_child>` are **not** visible
  441. in the Scene tree dock and are **not** persisted to disk. If you wish the node
  442. or scene to be visible in the scene tree dock and persisted to disk when saving
  443. the scene, you need to set the child node's :ref:`owner <class_Node_property_owner>`
  444. property to the currently edited scene root.
  445. If you are using ``@tool``:
  446. .. tabs::
  447. .. code-tab:: gdscript GDScript
  448. func _ready():
  449. var node = Node3D.new()
  450. add_child(node) # Parent could be any node in the scene
  451. # The line below is required to make the node visible in the Scene tree dock
  452. # and persist changes made by the tool script to the saved scene file.
  453. node.owner = get_tree().edited_scene_root
  454. .. code-tab:: csharp
  455. public override void _Ready()
  456. {
  457. var node = new Node3D();
  458. AddChild(node); // Parent could be any node in the scene
  459. // The line below is required to make the node visible in the Scene tree dock
  460. // and persist changes made by the tool script to the saved scene file.
  461. node.Owner = GetTree().EditedSceneRoot;
  462. }
  463. If you are using :ref:`EditorScript<class_EditorScript>`:
  464. .. tabs::
  465. .. code-tab:: gdscript GDScript
  466. func _run():
  467. # `parent` could be any node in the scene.
  468. var parent = get_scene().get_node("Parent")
  469. var node = Node3D.new()
  470. parent.add_child(node)
  471. # The line below is required to make the node visible in the Scene tree dock
  472. # and persist changes made by the tool script to the saved scene file.
  473. node.owner = get_scene()
  474. .. code-tab:: csharp
  475. public override void _Run()
  476. {
  477. // `parent` could be any node in the scene.
  478. var parent = GetScene().GetNode("Parent");
  479. var node = new Node3D();
  480. parent.AddChild(node);
  481. // The line below is required to make the node visible in the Scene tree dock
  482. // and persist changes made by the tool script to the saved scene file.
  483. node.Owner = GetScene();
  484. }
  485. .. warning::
  486. Using ``@tool`` improperly can yield many errors. It is advised to first
  487. write the code how you want it, and only then add the ``@tool`` annotation to
  488. the top. Also, make sure to separate code that runs in-editor from code that
  489. runs in-game. This way, you can find bugs more easily.