running_code_in_the_editor.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. Important information
  78. ---------------------
  79. Any other GDScript that your tool script uses must *also* be a tool. Any
  80. GDScript without ``@tool`` used by the editor will act like an empty file!
  81. Extending a ``@tool`` script does not automatically make the extending script
  82. a ``@tool``. Omitting ``@tool`` from the extending script will disable tool
  83. behavior from the super class. Therefore the extending script should also
  84. specify the ``@tool`` annotation.
  85. Modifications in the editor are permanent. For example, in the next
  86. section when we remove the script, the node will keep its rotation. Be careful
  87. to avoid making unwanted modifications.
  88. Try ``@tool`` out
  89. -----------------
  90. Add a ``Sprite2D`` node to your scene and set the texture to Godot icon. Attach
  91. and open a script, and change it to this:
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. @tool
  95. extends Sprite2D
  96. func _process(delta):
  97. rotation += PI * delta
  98. .. code-tab:: csharp
  99. using Godot;
  100. [Tool]
  101. public partial class MySprite : Sprite2D
  102. {
  103. public override void _Process(double delta)
  104. {
  105. Rotation += Mathf.Pi * (float)delta;
  106. }
  107. }
  108. Save the script and return to the editor. You should now see your object rotate.
  109. If you run the game, it will also rotate.
  110. .. image:: img/rotating_in_editor.gif
  111. .. note::
  112. If you don't see the changes, reload the scene (close it and open it again).
  113. Now let's choose which code runs when. Modify your ``_process()`` function to
  114. look like this:
  115. .. tabs::
  116. .. code-tab:: gdscript GDScript
  117. func _process(delta):
  118. if Engine.is_editor_hint():
  119. rotation += PI * delta
  120. else:
  121. rotation -= PI * delta
  122. .. code-tab:: csharp
  123. public override void _Process(double delta)
  124. {
  125. if (Engine.IsEditorHint())
  126. {
  127. Rotation += Mathf.Pi * (float)delta;
  128. }
  129. else
  130. {
  131. Rotation -= Mathf.Pi * (float)delta;
  132. }
  133. }
  134. Save the script. Now the object will spin clockwise in the editor, but if you
  135. run the game, it will spin counter-clockwise.
  136. Editing variables
  137. -----------------
  138. Add and export a variable speed to the script. To update the speed and also reset the rotation
  139. angle add a setter ``set(new_speed)`` which is executed with the input from the inspector. Modify
  140. ``_process()`` to include the rotation speed.
  141. .. tabs::
  142. .. code-tab:: gdscript GDScript
  143. @tool
  144. extends Sprite2D
  145. @export var speed = 1:
  146. # Update speed and reset the rotation.
  147. set(new_speed):
  148. speed = new_speed
  149. rotation = 0
  150. func _process(delta):
  151. rotation += PI * delta * speed
  152. .. code-tab:: csharp
  153. using Godot;
  154. [Tool]
  155. public partial class MySprite : Sprite2D
  156. {
  157. private float _speed = 1;
  158. [Export]
  159. public float Speed
  160. {
  161. get => _speed;
  162. set
  163. {
  164. // Update speed and reset the rotation.
  165. _speed = value;
  166. Rotation = 0;
  167. }
  168. }
  169. public override void _Process(double delta)
  170. {
  171. Rotation += Mathf.Pi * (float)delta * speed;
  172. }
  173. }
  174. .. note::
  175. Code from other nodes doesn't run in the editor. Your access to other nodes
  176. is limited. You can access the tree and nodes, and their default properties,
  177. but you can't access user variables. If you want to do so, other nodes have
  178. to run in the editor too. Autoload nodes cannot be accessed in the editor at
  179. all.
  180. Reporting node configuration warnings
  181. -------------------------------------
  182. Godot uses a *node configuration warning* system to warn users about incorrectly
  183. configured nodes. When a node isn't configured correctly, a yellow warning sign
  184. appears next to the node's name in the Scene dock. When you hover or click on
  185. the icon, a warning message pops up. You can use this feature in your scripts to
  186. help you and your team avoid mistakes when setting up scenes.
  187. When using node configuration warnings, when any value that should affect or
  188. remove the warning changes, you need to call
  189. :ref:`update_configuration_warnings<class_Node_method_update_configuration_warnings>` .
  190. By default, the warning only updates when closing and reopening the scene.
  191. .. tabs::
  192. .. code-tab:: gdscript GDScript
  193. # Use setters to update the configuration warning automatically.
  194. @export var title = "":
  195. set(p_title):
  196. if p_title != title:
  197. title = p_title
  198. update_configuration_warnings()
  199. @export var description = "":
  200. set(p_description):
  201. if p_description != description:
  202. description = p_description
  203. update_configuration_warnings()
  204. func _get_configuration_warnings():
  205. var warnings = []
  206. if title == "":
  207. warnings.append("Please set `title` to a non-empty value.")
  208. if description.length() >= 100:
  209. warnings.append("`description` should be less than 100 characters long.")
  210. # Returning an empty array means "no warning".
  211. return warnings
  212. Running one-off scripts using EditorScript
  213. ------------------------------------------
  214. Sometimes, you need to run code just one time to automate a certain task that is
  215. not available in the editor out of the box. Some examples might be:
  216. - Use as a playground for GDScript or C# scripting without having to run a project.
  217. ``print()`` output is displayed in the editor Output panel.
  218. - Scale all light nodes in the currently edited scene, as you noticed your level
  219. ends up looking too dark or too bright after placing lights where desired.
  220. - Replace nodes that were copy-pasted with scene instances to make them easier
  221. to modify later.
  222. This is available in Godot by extending :ref:`class_EditorScript` in a script.
  223. This provides a way to run individual scripts in the editor without having to
  224. create an editor plugin.
  225. To create an EditorScript, right-click a folder or empty space in the FileSystem
  226. dock then choose **New > Script...**. In the script creation dialog, click the
  227. tree icon to choose an object to extend from (or enter ``EditorScript`` directly
  228. in the field on the left, though note this is case-sensitive):
  229. .. figure:: img/running_code_in_the_editor_creating_editor_script.webp
  230. :align: center
  231. :alt: Creating an editor script in the script editor creation dialog
  232. Creating an editor script in the script editor creation dialog
  233. This will automatically select a script template that is suited for
  234. EditorScripts, with a ``_run()`` method already inserted:
  235. ::
  236. @tool
  237. extends EditorScript
  238. # Called when the script is executed (using File -> Run in Script Editor).
  239. func _run():
  240. pass
  241. This ``_run()`` method is executed when you use **File > Run** or the keyboard
  242. shortcut :kbd:`Ctrl + Shift + X` while the EditorScript is the currently open
  243. script in the script editor. This keyboard shortcut is only effective when
  244. currently focused on the script editor.
  245. Scripts that extend EditorScript must be ``@tool`` scripts to function.
  246. .. warning::
  247. EditorScripts have no undo/redo functionality, so **make sure to save your
  248. scene before running one** if the script is designed to modify any data.
  249. To access nodes in the currently edited scene, use the
  250. :ref:`EditorScript.get_scene <class_EditorScript_method_get_scene>` method which
  251. returns the root Node of the currently edited scene. Here's an example that
  252. recursively gets all nodes in the currently edited scene and doubles the range
  253. of all OmniLight3D nodes:
  254. ::
  255. @tool
  256. extends EditorScript
  257. func _run():
  258. for node in get_all_children(get_scene()):
  259. if node is OmniLight3D:
  260. # Don't operate on instanced subscene children, as changes are lost
  261. # when reloading the scene.
  262. # See the "Instancing scenes" section below for a description of `owner`.
  263. var is_instanced_subscene_child = node != get_scene() and node.owner != get_scene()
  264. if not is_instanced_subscene_child:
  265. node.omni_range *= 2.0
  266. # This function is recursive: it calls itself to get lower levels of child nodes as needed.
  267. # `children_acc` is the accumulator parameter that allows this function to work.
  268. # It should be left to its default value when you call this function directly.
  269. func get_all_children(in_node, children_acc = []):
  270. children_acc.push_back(in_node)
  271. for child in in_node.get_children():
  272. children_acc = get_all_children(child, children_acc)
  273. return children_acc
  274. .. tip::
  275. You can change the currently edited scene at the top of the editor even
  276. while the Script view is open. This will affect the return value of
  277. :ref:`EditorScript.get_scene <class_EditorScript_method_get_scene>`, so make
  278. sure you've selected the scene you intend to iterate upon before running
  279. the script.
  280. Instancing scenes
  281. -----------------
  282. You can instantiate packed scenes normally and add them to the scene currently
  283. opened in the editor. By default, nodes or scenes added with
  284. :ref:`Node.add_child(node) <class_Node_method_add_child>` are **not** visible
  285. in the Scene tree dock and are **not** persisted to disk. If you wish the node
  286. or scene to be visible in the scene tree dock and persisted to disk when saving
  287. the scene, you need to set the child node's :ref:`owner <class_Node_property_owner>`
  288. property to the currently edited scene root.
  289. If you are using ``@tool``:
  290. .. tabs::
  291. .. code-tab:: gdscript GDScript
  292. func _ready():
  293. var node = Node3D.new()
  294. add_child(node) # Parent could be any node in the scene
  295. # The line below is required to make the node visible in the Scene tree dock
  296. # and persist changes made by the tool script to the saved scene file.
  297. node.owner = get_tree().edited_scene_root
  298. .. code-tab:: csharp
  299. public override void _Ready()
  300. {
  301. var node = new Node3D();
  302. AddChild(node); // Parent could be any node in the scene
  303. // The line below is required to make the node visible in the Scene tree dock
  304. // and persist changes made by the tool script to the saved scene file.
  305. node.Owner = GetTree().EditedSceneRoot;
  306. }
  307. If you are using :ref:`EditorScript<class_EditorScript>`:
  308. .. tabs::
  309. .. code-tab:: gdscript GDScript
  310. func _run():
  311. # `parent` could be any node in the scene.
  312. var parent = get_scene().get_node("Parent")
  313. var node = Node3D.new()
  314. parent.add_child(node)
  315. # The line below is required to make the node visible in the Scene tree dock
  316. # and persist changes made by the tool script to the saved scene file.
  317. node.owner = get_scene()
  318. .. code-tab:: csharp
  319. public override void _Run()
  320. {
  321. // `parent` could be any node in the scene.
  322. var parent = GetScene().GetNode("Parent");
  323. var node = new Node3D();
  324. parent.AddChild(node);
  325. // The line below is required to make the node visible in the Scene tree dock
  326. // and persist changes made by the tool script to the saved scene file.
  327. node.Owner = GetScene();
  328. }
  329. .. warning::
  330. Using ``@tool`` improperly can yield many errors. It is advised to first
  331. write the code how you want it, and only then add the ``@tool`` annotation to
  332. the top. Also, make sure to separate code that runs in-editor from code that
  333. runs in-game. This way, you can find bugs more easily.