godot_interfaces.rst 17 KB

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