godot_interfaces.rst 18 KB

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