godot_interfaces.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. .. _doc_godot_interfaces:
  2. Godot interfaces
  3. ================
  4. Often one needs scripts that rely on other objects for features. There
  5. are 2 parts to this process:
  6. 1. Acquiring a reference to the object that presumably has the features.
  7. 2. Accessing the data or logic from the object.
  8. The rest of this tutorial outlines the various ways of doing all this.
  9. Acquiring object references
  10. ---------------------------
  11. For all :ref:`Object <class_Object>`\s, the most basic way of referencing them
  12. is to get a reference to an existing object from another acquired instance.
  13. .. tabs::
  14. .. code-tab:: gdscript GDScript
  15. var obj = node.object # Property access.
  16. var obj = node.get_object() # Method access.
  17. .. code-tab:: csharp
  18. GodotObject obj = node.Object; // Property access.
  19. GodotObject obj = node.GetObject(); // Method access.
  20. The same principle applies for :ref:`RefCounted <class_RefCounted>` objects.
  21. While users often access :ref:`Node <class_Node>` and
  22. :ref:`Resource <class_Resource>` this way, alternative measures are available.
  23. Instead of property or method access, one can get Resources by load
  24. access.
  25. .. tabs::
  26. .. code-tab:: gdscript GDScript
  27. # If you need an "export const var" (which doesn't exist), use a conditional
  28. # setter for a tool script that checks if it's executing in the editor.
  29. # The `@tool` annotation must be placed at the top of the script.
  30. @tool
  31. # Load resource during scene load.
  32. var preres = preload(path)
  33. # Load resource when program reaches statement.
  34. var res = load(path)
  35. # Note that users load scenes and scripts, by convention, with PascalCase
  36. # names (like typenames), often into constants.
  37. const MyScene = preload("my_scene.tscn") # Static load
  38. const MyScript = preload("my_script.gd")
  39. # This type's value varies, i.e. it is a variable, so it uses snake_case.
  40. @export var script_type: Script
  41. # Must configure from the editor, defaults to null.
  42. export var const_script: Script:
  43. set(value):
  44. if Engine.is_editor_hint():
  45. const_script = value
  46. # Warn users if the value hasn't been set.
  47. func _get_configuration_warnings():
  48. if not const_script:
  49. return ["Must initialize property 'const_script'."]
  50. return []
  51. .. code-tab:: csharp
  52. // Tool script added for the sake of the "const [Export]" example.
  53. [Tool]
  54. public MyType
  55. {
  56. // Property initializations load during Script instancing, i.e. .new().
  57. // No "preload" loads during scene load exists in C#.
  58. // Initialize with a value. Editable at runtime.
  59. public Script MyScript = GD.Load<Script>("MyScript.cs");
  60. // Initialize with same value. Value cannot be changed.
  61. public readonly Script MyConstScript = GD.Load<Script>("MyScript.cs");
  62. // Like 'readonly' due to inaccessible setter.
  63. // But, value can be set during constructor, i.e. MyType().
  64. public Script Library { get; } = GD.Load<Script>("res://addons/plugin/library.gd");
  65. // If need a "const [Export]" (which doesn't exist), use a
  66. // conditional setter for a tool script that checks if it's executing
  67. // in the editor.
  68. private PackedScene _enemyScn;
  69. [Export]
  70. public PackedScene EnemyScn
  71. {
  72. get { return _enemyScn; }
  73. set
  74. {
  75. if (Engine.IsEditorHint())
  76. {
  77. _enemyScn = value;
  78. }
  79. }
  80. };
  81. // Warn users if the value hasn't been set.
  82. public String _GetConfigurationWarnings()
  83. {
  84. if (EnemyScn == null)
  85. return "Must initialize property 'EnemyScn'.";
  86. return "";
  87. }
  88. }
  89. Note the following:
  90. 1. There are many ways in which a language can load such resources.
  91. 2. When designing how objects will access data, don't forget
  92. that one can pass resources around as references as well.
  93. 3. Keep in mind that loading a resource fetches the cached resource
  94. instance maintained by the engine. To get a new object, one must
  95. :ref:`duplicate <class_Resource_method_duplicate>` an existing reference
  96. or instantiate one from scratch with ``new()``.
  97. Nodes likewise have an alternative access point: the SceneTree.
  98. .. tabs::
  99. .. code-tab:: gdscript GDScript
  100. extends Node
  101. # Slow.
  102. func dynamic_lookup_with_dynamic_nodepath():
  103. print(get_node("Child"))
  104. # Faster. GDScript only.
  105. func dynamic_lookup_with_cached_nodepath():
  106. print($Child)
  107. # Fastest. Doesn't break if node moves later.
  108. # Note that `@onready` annotation is GDScript-only.
  109. # Other languages must do...
  110. # var child
  111. # func _ready():
  112. # child = get_node("Child")
  113. @onready var child = $Child
  114. func lookup_and_cache_for_future_access():
  115. print(child)
  116. # Fastest. Doesn't break if node is moved in the Scene tree dock.
  117. # Node must be selected in the inspector as it's an exported property.
  118. @export var child: Node
  119. func lookup_and_cache_for_future_access():
  120. print(child)
  121. # Delegate reference assignment to an external source.
  122. # Con: need to perform a validation check.
  123. # Pro: node makes no requirements of its external structure.
  124. # 'prop' can come from anywhere.
  125. var prop
  126. func call_me_after_prop_is_initialized_by_parent():
  127. # Validate prop in one of three ways.
  128. # Fail with no notification.
  129. if not prop:
  130. return
  131. # Fail with an error message.
  132. if not prop:
  133. printerr("'prop' wasn't initialized")
  134. return
  135. # Fail and terminate.
  136. # NOTE: Scripts run from a release export template don't run `assert`s.
  137. assert(prop, "'prop' wasn't initialized")
  138. # Use an autoload.
  139. # Dangerous for typical nodes, but useful for true singleton nodes
  140. # that manage their own data and don't interfere with other objects.
  141. func reference_a_global_autoloaded_variable():
  142. print(globals)
  143. print(globals.prop)
  144. print(globals.my_getter())
  145. .. code-tab:: csharp
  146. using Godot;
  147. using System;
  148. using System.Diagnostics;
  149. public class MyNode : Node
  150. {
  151. // Slow
  152. public void DynamicLookupWithDynamicNodePath()
  153. {
  154. GD.Print(GetNode("Child"));
  155. }
  156. // Fastest. Lookup node and cache for future access.
  157. // Doesn't break if node moves later.
  158. private Node _child;
  159. public void _Ready()
  160. {
  161. _child = GetNode("Child");
  162. }
  163. public void LookupAndCacheForFutureAccess()
  164. {
  165. GD.Print(_child);
  166. }
  167. // Delegate reference assignment to an external source.
  168. // Con: need to perform a validation check.
  169. // Pro: node makes no requirements of its external structure.
  170. // 'prop' can come from anywhere.
  171. public object Prop { get; set; }
  172. public void CallMeAfterPropIsInitializedByParent()
  173. {
  174. // Validate prop in one of three ways.
  175. // Fail with no notification.
  176. if (prop == null)
  177. {
  178. return;
  179. }
  180. // Fail with an error message.
  181. if (prop == null)
  182. {
  183. GD.PrintErr("'Prop' wasn't initialized");
  184. return;
  185. }
  186. // Fail with an exception.
  187. if (prop == null)
  188. {
  189. throw new InvalidOperationException("'Prop' wasn't initialized.");
  190. }
  191. // Fail and terminate.
  192. // Note: Scripts run from a release export template don't run `Debug.Assert`s.
  193. Debug.Assert(Prop, "'Prop' wasn't initialized");
  194. }
  195. // Use an autoload.
  196. // Dangerous for typical nodes, but useful for true singleton nodes
  197. // that manage their own data and don't interfere with other objects.
  198. public void ReferenceAGlobalAutoloadedVariable()
  199. {
  200. MyNode globals = GetNode<MyNode>("/root/Globals");
  201. GD.Print(globals);
  202. GD.Print(globals.Prop);
  203. GD.Print(globals.MyGetter());
  204. }
  205. };
  206. .. _doc_accessing_data_or_logic_from_object:
  207. Accessing data or logic from an object
  208. --------------------------------------
  209. Godot's scripting API is duck-typed. This means that if a script executes an
  210. operation, Godot doesn't validate that it supports the operation by **type**.
  211. It instead checks that the object **implements** the individual method.
  212. For example, the :ref:`CanvasItem <class_CanvasItem>` class has a ``visible``
  213. property. All properties exposed to the scripting API are in fact a setter and
  214. getter pair bound to a name. If one tried to access
  215. :ref:`CanvasItem.visible <class_CanvasItem_property_visible>`, then Godot would do the
  216. following checks, in order:
  217. - If the object has a script attached, it will attempt to set the property
  218. through the script. This leaves open the opportunity for scripts to override
  219. a property defined on a base object by overriding the setter method for the
  220. property.
  221. - If the script does not have the property, it performs a HashMap lookup in
  222. the ClassDB for the "visible" property against the CanvasItem class and all
  223. of its inherited types. If found, it will call the bound setter or getter.
  224. For more information about HashMaps, see the
  225. :ref:`data preferences <doc_data_preferences>` docs.
  226. - If not found, it does an explicit check to see if the user wants to access
  227. the "script" or "meta" properties.
  228. - If not, it checks for a ``_set``/``_get`` implementation (depending on type
  229. of access) in the CanvasItem and its inherited types. These methods can
  230. execute logic that gives the impression that the Object has a property. This
  231. is also the case with the ``_get_property_list`` method.
  232. - Note that this happens even for non-legal symbol names, such as names
  233. starting with a digit or containing a slash.
  234. As a result, this duck-typed system can locate a property either in the script,
  235. the object's class, or any class that object inherits, but only for things
  236. which extend Object.
  237. Godot provides a variety of options for performing runtime checks on these
  238. accesses:
  239. - A duck-typed property access. These will be property checks (as described above).
  240. If the operation isn't supported by the object, execution will halt.
  241. .. tabs::
  242. .. code-tab:: gdscript GDScript
  243. # All Objects have duck-typed get, set, and call wrapper methods.
  244. get_parent().set("visible", false)
  245. # Using a symbol accessor, rather than a string in the method call,
  246. # will implicitly call the `set` method which, in turn, calls the
  247. # setter method bound to the property through the property lookup
  248. # sequence.
  249. get_parent().visible = false
  250. # Note that if one defines a _set and _get that describe a property's
  251. # existence, but the property isn't recognized in any _get_property_list
  252. # method, then the set() and get() methods will work, but the symbol
  253. # access will claim it can't find the property.
  254. .. code-tab:: csharp
  255. // All Objects have duck-typed Get, Set, and Call wrapper methods.
  256. GetParent().Set("visible", false);
  257. // C# is a static language, so it has no dynamic symbol access, e.g.
  258. // `GetParent().Visible = false` won't work.
  259. - A method check. In the case of
  260. :ref:`CanvasItem.visible <class_CanvasItem_property_visible>`, one can
  261. access the methods, ``set_visible`` and ``is_visible`` like any other method.
  262. .. tabs::
  263. .. code-tab:: gdscript GDScript
  264. var child = get_child(0)
  265. # Dynamic lookup.
  266. child.call("set_visible", false)
  267. # Symbol-based dynamic lookup.
  268. # GDScript aliases this into a 'call' method behind the scenes.
  269. child.set_visible(false)
  270. # Dynamic lookup, checks for method existence first.
  271. if child.has_method("set_visible"):
  272. child.set_visible(false)
  273. # Cast check, followed by dynamic lookup.
  274. # Useful when you make multiple "safe" calls knowing that the class
  275. # implements them all. No need for repeated checks.
  276. # Tricky if one executes a cast check for a user-defined type as it
  277. # forces more dependencies.
  278. if child is CanvasItem:
  279. child.set_visible(false)
  280. child.show_on_top = true
  281. # If one does not wish to fail these checks without notifying users,
  282. # one can use an assert instead. These will trigger runtime errors
  283. # immediately if not true.
  284. assert(child.has_method("set_visible"))
  285. assert(child.is_in_group("offer"))
  286. assert(child is CanvasItem)
  287. # Can also use object labels to imply an interface, i.e. assume it
  288. # implements certain methods.
  289. # There are two types, both of which only exist for Nodes: Names and
  290. # Groups.
  291. # Assuming...
  292. # A "Quest" object exists and 1) that it can "complete" or "fail" and
  293. # that it will have text available before and after each state...
  294. # 1. Use a name.
  295. var quest = $Quest
  296. print(quest.text)
  297. quest.complete() # or quest.fail()
  298. print(quest.text) # implied new text content
  299. # 2. Use a group.
  300. for a_child in get_children():
  301. if a_child.is_in_group("quest"):
  302. print(quest.text)
  303. quest.complete() # or quest.fail()
  304. print(quest.text) # implied new text content
  305. # Note that these interfaces are project-specific conventions the team
  306. # defines (which means documentation! But maybe worth it?).
  307. # Any script that conforms to the documented "interface" of the name or
  308. # group can fill in for it.
  309. .. code-tab:: csharp
  310. Node child = GetChild(0);
  311. // Dynamic lookup.
  312. child.Call("SetVisible", false);
  313. // Dynamic lookup, checks for method existence first.
  314. if (child.HasMethod("SetVisible"))
  315. {
  316. child.Call("SetVisible", false);
  317. }
  318. // Use a group as if it were an "interface", i.e. assume it implements
  319. // certain methods.
  320. // Requires good documentation for the project to keep it reliable
  321. // (unless you make editor tools to enforce it at editor time).
  322. // Note, this is generally not as good as using an actual interface in
  323. // C#, but you can't set C# interfaces from the editor since they are
  324. // language-level features.
  325. if (child.IsInGroup("Offer"))
  326. {
  327. child.Call("Accept");
  328. child.Call("Reject");
  329. }
  330. // Cast check, followed by static lookup.
  331. CanvasItem ci = GetParent() as CanvasItem;
  332. if (ci != null)
  333. {
  334. ci.SetVisible(false);
  335. // useful when you need to make multiple safe calls to the class
  336. ci.ShowOnTop = true;
  337. }
  338. // If one does not wish to fail these checks without notifying users,
  339. // one can use an assert instead. These will trigger runtime errors
  340. // immediately if not true.
  341. Debug.Assert(child.HasMethod("set_visible"));
  342. Debug.Assert(child.IsInGroup("offer"));
  343. Debug.Assert(CanvasItem.InstanceHas(child));
  344. // Can also use object labels to imply an interface, i.e. assume it
  345. // implements certain methods.
  346. // There are two types, both of which only exist for Nodes: Names and
  347. // Groups.
  348. // Assuming...
  349. // A "Quest" object exists and 1) that it can "Complete" or "Fail" and
  350. // that it will have Text available before and after each state...
  351. // 1. Use a name.
  352. Node quest = GetNode("Quest");
  353. GD.Print(quest.Get("Text"));
  354. quest.Call("Complete"); // or "Fail".
  355. GD.Print(quest.Get("Text")); // Implied new text content.
  356. // 2. Use a group.
  357. foreach (Node AChild in GetChildren())
  358. {
  359. if (AChild.IsInGroup("quest"))
  360. {
  361. GD.Print(quest.Get("Text"));
  362. quest.Call("Complete"); // or "Fail".
  363. GD.Print(quest.Get("Text")); // Implied new text content.
  364. }
  365. }
  366. // Note that these interfaces are project-specific conventions the team
  367. // defines (which means documentation! But maybe worth it?).
  368. // Any script that conforms to the documented "interface" of the
  369. // name or group can fill in for it. Also note that in C#, these methods
  370. // will be slower than static accesses with traditional interfaces.
  371. - Outsource the access to a :ref:`Callable <class_Callable>`. These may be useful
  372. in cases where one needs the max level of freedom from dependencies. In
  373. this case, one relies on an external context to setup the method.
  374. .. tabs::
  375. .. code-tab:: gdscript GDScript
  376. # child.gd
  377. extends Node
  378. var fn = null
  379. func my_method():
  380. if fn:
  381. fn.call()
  382. # parent.gd
  383. extends Node
  384. @onready var child = $Child
  385. func _ready():
  386. child.fn = print_me
  387. child.my_method()
  388. func print_me():
  389. print(name)
  390. .. code-tab:: csharp
  391. // Child.cs
  392. using Godot;
  393. public partial class Child : Node
  394. {
  395. public Callable? Callable { get; set; }
  396. public void MyMethod()
  397. {
  398. Callable?.Call();
  399. }
  400. }
  401. // Parent.cs
  402. using Godot;
  403. public partial class Parent : Node
  404. {
  405. private Child _child;
  406. public void _Ready()
  407. {
  408. _child = GetNode<Child>("Child");
  409. _child.Callable = Callable.From(PrintMe);
  410. _child.MyMethod();
  411. }
  412. public void PrintMe() {
  413. {
  414. GD.Print(Name);
  415. }
  416. }
  417. These strategies contribute to Godot's flexible design. Between them, users
  418. have a breadth of tools to meet their specific needs.