godot_interfaces.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 : extends Object
  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 or
  93. 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. # Compiled scripts in final binary do not include assert statements
  129. assert prop.
  130. # Use an autoload.
  131. # Dangerous for typical nodes, but useful for true singleton nodes
  132. # that manage their own data and don't interfere with other objects.
  133. func reference_a_global_autoloaded_variable():
  134. print(globals)
  135. print(globals.prop)
  136. print(globals.my_getter())
  137. .. code-tab:: csharp
  138. public class MyNode
  139. {
  140. // Slow, dynamic lookup with dynamic NodePath.
  141. public void Method1()
  142. {
  143. GD.Print(GetNode(NodePath("Child")));
  144. }
  145. // Fastest. Lookup node and cache for future access.
  146. // Doesn't break if node moves later.
  147. public Node Child;
  148. public void _Ready()
  149. {
  150. Child = GetNode(NodePath("Child"));
  151. }
  152. public void Method2()
  153. {
  154. GD.Print(Child);
  155. }
  156. // Delegate reference assignment to an external source
  157. // Con: need to perform a validation check
  158. // Pro: node makes no requirements of its external structure.
  159. // 'prop' can come from anywhere.
  160. public object Prop;
  161. public void CallMeAfterPropIsInitializedByParent()
  162. {
  163. // Validate prop in one of three ways.
  164. // Fail with no notification.
  165. if (prop == null)
  166. {
  167. return;
  168. }
  169. // Fail with an error message.
  170. if (prop == null)
  171. {
  172. GD.PrintErr("'Prop' wasn't initialized");
  173. return;
  174. }
  175. // Fail and terminate.
  176. Debug.Assert(Prop, "'Prop' wasn't initialized");
  177. }
  178. // Use an autoload.
  179. // Dangerous for typical nodes, but useful for true singleton nodes
  180. // that manage their own data and don't interfere with other objects.
  181. public void ReferenceAGlobalAutoloadedVariable()
  182. {
  183. Node globals = GetNode(NodePath("/root/Globals"));
  184. GD.Print(globals);
  185. GD.Print(globals.prop);
  186. GD.Print(globals.my_getter());
  187. }
  188. };
  189. Accessing data or logic from an object
  190. --------------------------------------
  191. Godot's scripting API is duck-typed. This means that if a script executes an
  192. operation, Godot doesn't validate that it supports the operation by **type**.
  193. It instead checks that the object **implements** the individual method.
  194. For example, the :ref:`CanvasItem <class_CanvasItem>` class has a ``visible``
  195. property. All properties exposed to the scripting API are in fact a setter and
  196. getter pair bound to a name. If one tried to access
  197. :ref:`CanvasItem.visible <class_CanvasItem_property_visible>`, then Godot would do the
  198. following checks, in order:
  199. - If the object has a script attached, it will attempt to set the property
  200. through the script. This leaves open the opportunity for scripts to override
  201. a property defined on a base object by overriding the setter method for the
  202. property.
  203. - If the script does not have the property, it performs a HashMap lookup in
  204. the ClassDB for the "visible" property against the CanvasItem class and all
  205. of its inherited types. If found, it will call the bound setter or getter.
  206. For more information about HashMaps, see the
  207. :ref:`data preferences <doc_data_preferences>` docs.
  208. - If not found, it does an explicit check to see if the user wants to access
  209. the "script" or "meta" properties.
  210. - If not, it checks for a ``_set``/``_get`` implementation (depending on type
  211. of access) in the CanvasItem and its inherited types. These methods can
  212. execute logic that gives the impression that the Object has a property. This
  213. is also the case with the ``_get_property_list`` method.
  214. - Note that this happens even for non-legal symbol names such as in the
  215. case of :ref:`TileSet <class_TileSet>`'s "1/tile_name" property. This
  216. refers to the name of the tile with ID 1, i.e.
  217. :ref:`TileSet.tile_get_name(1) <class_TileSet_method_tile_get_name>`.
  218. As a result, this duck-typed system can locate a property either in the script,
  219. the object's class, or any class that object inherits, but only for things
  220. which extend Object.
  221. Godot provides a variety of options for performing runtime checks on these
  222. accesses:
  223. - A duck-typed property access. These will property check (as described above).
  224. If the operation isn't supported by the object, execution will halt.
  225. .. tabs::
  226. .. code-tab:: gdscript GDScript
  227. # All Objects have duck-typed get, set, and call wrapper methods.
  228. get_parent().set("visible", false)
  229. # Using a symbol accessor, rather than a string in the method call,
  230. # will implicitly call the `set` method which, in turn, calls the
  231. # setter method bound to the property through the property lookup
  232. # sequence.
  233. get_parent().visible = false
  234. # Note that if one defines a _set and _get that describe a property's
  235. # existence, but the property isn't recognized in any _get_property_list
  236. # method, then the set() and get() methods will work, but the symbol
  237. # access will claim it can't find the property.
  238. .. code-tab:: csharp
  239. // All Objects have duck-typed Get, Set, and Call wrapper methods.
  240. GetParent().Set("visible", false);
  241. // C# is a static language, so it has no dynamic symbol access, e.g.
  242. // `GetParent().Visible = false` won't work.
  243. - A method check. In the case of
  244. :ref:`CanvasItem.visible <class_CanvasItem_property_visible>`, one can
  245. access the methods, ``set_visible`` and ``is_visible`` like any other method.
  246. .. tabs::
  247. .. code-tab:: gdscript GDScript
  248. var child = get_child(0)
  249. # Dynamic lookup.
  250. child.call("set_visible", false)
  251. # Symbol-based dynamic lookup.
  252. # GDScript aliases this into a 'call' method behind the scenes.
  253. child.set_visible(false)
  254. # Dynamic lookup, checks for method existence first.
  255. if child.has("set_visible"):
  256. child.set_visible(false)
  257. # Cast check, followed by dynamic lookup
  258. # Useful when you make multiple "safe" calls knowing that the class
  259. # implements them all. No need for repeated checks.
  260. # Tricky if one executes a cast check for a user-defined type as it
  261. # forces more dependencies.
  262. if child is CanvasItem:
  263. child.set_visible(false)
  264. child.show_on_top = true
  265. # If one does not wish to fail these checks without notifying users, one
  266. # can use an assert instead. These will trigger runtime errors
  267. # immediately if not true.
  268. assert child.has("set_visible")
  269. assert child.is_in_group("offer")
  270. assert child is CanvasItem
  271. # Can also use object labels to imply an interface, i.e. assume it implements certain methods.
  272. # There are two types, both of which only exist for Nodes: Names and Groups
  273. # Assuming...
  274. # A "Quest" object exists and 1) that it can "complete" or "fail" and
  275. # that it will have text available before and after each state...
  276. # 1. Use a name.
  277. var quest = $Quest
  278. print(quest.text)
  279. quest.complete() # or quest.fail()
  280. print(quest.text) # implied new text content
  281. # 2. Use a group.
  282. for a_child in get_children():
  283. if a_child.is_in_group("quest"):
  284. print(quest.text)
  285. quest.complete() # or quest.fail()
  286. print(quest.text) # implied new text content
  287. # Note that these interfaces are project-specific conventions the team
  288. # defines (which means documentation! But maybe worth it?).
  289. # Any script that conforms to the documented "interface" of the name/group can fill in for it.
  290. .. code-tab:: csharp
  291. Node child = GetChild(0);
  292. // Dynamic lookup.
  293. child.Call("SetVisible", false);
  294. // Dynamic lookup, checks for method existence first.
  295. if (child.HasMethod("SetVisible"))
  296. {
  297. child.Call("SetVisible", false);
  298. }
  299. // Use a group as if it were an "interface", i.e. assume it implements certain methods
  300. // requires good documentation for the project to keep it reliable (unless you make
  301. // editor tools to enforce it at editor time.
  302. // Note, this is generally not as good as using an actual interface in C#,
  303. // but you can't set C# interfaces from the editor since they are
  304. // language-level features.
  305. if (child.IsInGroup("Offer"))
  306. {
  307. child.Call("Accept");
  308. child.Call("Reject");
  309. }
  310. // Cast check, followed by static lookup.
  311. CanvasItem ci = GetParent() as CanvasItem;
  312. if (ci != null)
  313. {
  314. ci.SetVisible(false);
  315. // useful when you need to make multiple safe calls to the class
  316. ci.ShowOnTop = true;
  317. }
  318. // If one does not wish to fail these checks without notifying users, one
  319. // can use an assert instead. These will trigger runtime errors
  320. // immediately if not true.
  321. Debug.Assert(child.HasMethod("set_visible"));
  322. Debug.Assert(child.IsInGroup("offer"));
  323. Debug.Assert(CanvasItem.InstanceHas(child));
  324. // Can also use object labels to imply an interface, i.e. assume it implements certain methods.
  325. // There are two types, both of which only exist for Nodes: Names and Groups
  326. // Assuming...
  327. // A "Quest" object exists and 1) that it can "Complete" or "Fail" and
  328. // that it will have Text available before and after each state...
  329. // 1. Use a name.
  330. Node quest = GetNode("Quest");
  331. GD.Print(quest.Get("Text"));
  332. quest.Call("Complete"); // or "Fail".
  333. GD.Print(quest.Get("Text")); // Implied new text content.
  334. // 2. Use a group.
  335. foreach (Node AChild in GetChildren())
  336. {
  337. if (AChild.IsInGroup("quest"))
  338. {
  339. GD.Print(quest.Get("Text"));
  340. quest.Call("Complete"); // or "Fail".
  341. GD.Print(quest.Get("Text")); // Implied new text content.
  342. }
  343. }
  344. // Note that these interfaces are project-specific conventions the team
  345. // defines (which means documentation! But maybe worth it?)..
  346. // Any script that conforms to the documented "interface" of the
  347. // name/group can fill in for it. Also note that in C#, these methods
  348. // will be slower than static accesses with traditional interfaces.
  349. - Outsource the access to a :ref:`FuncRef <class_FuncRef>`. These may be useful
  350. in cases where one needs the max level of freedom from dependencies. In
  351. this case, one relies on an external context to setup the method.
  352. .. tabs::
  353. .. code-tab:: gdscript GDScript
  354. # child.gd
  355. extends Node
  356. var fn = null
  357. func my_method():
  358. if fn:
  359. fn.call_func()
  360. # parent.gd
  361. extends Node
  362. onready var child = $Child
  363. func _ready():
  364. child.fn = funcref(self, "print_me")
  365. child.my_method()
  366. func print_me():
  367. print(name)
  368. .. code-tab:: csharp
  369. // Child.cs
  370. public class Child extends Node
  371. {
  372. public FuncRef FN = null;
  373. public void MyMethod()
  374. {
  375. Debug.Assert(FN != null);
  376. FN.CallFunc();
  377. }
  378. }
  379. // Parent.cs
  380. public class Parent extends Node
  381. {
  382. public Node Child;
  383. public void _Ready()
  384. {
  385. Child = GetNode("Child");
  386. Child.Set("FN", GD.FuncRef(this, "PrintMe"));
  387. Child.MyMethod();
  388. }
  389. public void PrintMe() {
  390. {
  391. GD.Print(GetClass());
  392. }
  393. }
  394. These strategies contribute to Godot's flexible design. Between them, users
  395. have a breadth of tools to meet their specific needs.