cross_language_scripting.rst 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. .. _doc_cross_language_scripting:
  2. Cross-language scripting
  3. ========================
  4. Godot allows you to mix and match scripting languages to suit your needs.
  5. This means a single project can define nodes in both C# and GDScript.
  6. This page will go through the possible interactions between two nodes written
  7. in different languages.
  8. The following two scripts will be used as references throughout this page.
  9. .. tabs::
  10. .. code-tab:: gdscript GDScript
  11. extends Node
  12. var my_property: String = "my gdscript value":
  13. get:
  14. return my_property
  15. set(value):
  16. my_property = value
  17. signal my_signal
  18. func print_node_name(node: Node) -> void:
  19. print(node.get_name())
  20. func print_array(arr: Array) -> void:
  21. for element in arr:
  22. print(element)
  23. func print_n_times(msg: String, n: int) -> void:
  24. for i in range(n):
  25. print(msg)
  26. func my_signal_handler():
  27. print("The signal handler was called!")
  28. .. code-tab:: csharp
  29. using Godot;
  30. public partial class MyCSharpNode : Node
  31. {
  32. public string MyProperty { get; set; } = "my c# value";
  33. [Signal] public delegate void MySignalEventHandler();
  34. public void PrintNodeName(Node node)
  35. {
  36. GD.Print(node.Name);
  37. }
  38. public void PrintArray(string[] arr)
  39. {
  40. foreach (string element in arr)
  41. {
  42. GD.Print(element);
  43. }
  44. }
  45. public void PrintNTimes(string msg, int n)
  46. {
  47. for (int i = 0; i < n; ++i)
  48. {
  49. GD.Print(msg);
  50. }
  51. }
  52. public void MySignalHandler()
  53. {
  54. GD.Print("The signal handler was called!");
  55. }
  56. }
  57. Instantiating nodes
  58. -------------------
  59. If you're not using nodes from the scene tree, you'll probably want to
  60. instantiate nodes directly from the code.
  61. Instantiating C# nodes from GDScript
  62. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  63. Using C# from GDScript doesn't need much work. Once loaded
  64. (see :ref:`doc_gdscript_classes_as_resources`), the script can be instantiated
  65. with :ref:`new() <class_CSharpScript_method_new>`.
  66. .. code-block:: gdscript
  67. var MyCSharpScript = load("res://Path/To/MyCSharpNode.cs")
  68. var my_csharp_node = MyCSharpScript.new()
  69. .. warning::
  70. When creating ``.cs`` scripts, you should always keep in mind that the class
  71. Godot will use is the one named like the ``.cs`` file itself. If that class
  72. does not exist in the file, you'll see the following error:
  73. ``Invalid call. Nonexistent function `new` in base``.
  74. For example, MyCoolNode.cs should contain a class named MyCoolNode.
  75. The C# class needs to derive a Godot class, for example ``GodotObject``.
  76. Otherwise, the same error will occur.
  77. You also need to check your ``.cs`` file is referenced in the project's
  78. ``.csproj`` file. Otherwise, the same error will occur.
  79. Instantiating GDScript nodes from C#
  80. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  81. From the C# side, everything work the same way. Once loaded, the GDScript can
  82. be instantiated with :ref:`GDScript.New() <class_GDScript_method_new>`.
  83. .. code-block:: csharp
  84. var myGDScript = GD.Load<GDScript>("res://path/to/my_gd_script.gd");
  85. var myGDScriptNode = (GodotObject)myGDScript.New(); // This is a GodotObject.
  86. Here we are using an :ref:`class_Object`, but you can use type conversion like
  87. explained in :ref:`doc_c_sharp_features_type_conversion_and_casting`.
  88. Accessing fields
  89. ----------------
  90. Accessing C# fields from GDScript
  91. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  92. Accessing C# fields from GDScript is straightforward, you shouldn't have
  93. anything to worry about.
  94. .. code-block:: gdscript
  95. # Output: "my c# value".
  96. print(my_csharp_node.MyProperty)
  97. my_csharp_node.MyProperty = "MY C# VALUE"
  98. # Output: "MY C# VALUE".
  99. print(my_csharp_node.MyProperty)
  100. Accessing GDScript fields from C#
  101. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  102. As C# is statically typed, accessing GDScript from C# is a bit more
  103. convoluted. You will have to use :ref:`GodotObject.Get() <class_Object_method_get>`
  104. and :ref:`GodotObject.Set() <class_Object_method_set>`. The first argument is the name of the field you want to access.
  105. .. code-block:: csharp
  106. // Output: "my gdscript value".
  107. GD.Print(myGDScriptNode.Get("my_property"));
  108. myGDScriptNode.Set("my_property", "MY GDSCRIPT VALUE");
  109. // Output: "MY GDSCRIPT VALUE".
  110. GD.Print(myGDScriptNode.Get("my_property"));
  111. Keep in mind that when setting a field value you should only use types the
  112. GDScript side knows about.
  113. Essentially, you want to work with built-in types as described in :ref:`doc_gdscript` or classes extending :ref:`class_Object`.
  114. Calling methods
  115. ---------------
  116. Calling C# methods from GDScript
  117. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  118. Again, calling C# methods from GDScript should be straightforward. The
  119. marshalling process will do its best to cast the arguments to match
  120. function signatures.
  121. If that's impossible, you'll see the following error: ``Invalid call. Nonexistent function `FunctionName```.
  122. .. code-block:: gdscript
  123. # Output: "my_gd_script_node" (or name of node where this code is placed).
  124. my_csharp_node.PrintNodeName(self)
  125. # This line will fail.
  126. # my_csharp_node.PrintNodeName()
  127. # Outputs "Hello there!" twice, once per line.
  128. my_csharp_node.PrintNTimes("Hello there!", 2)
  129. # Output: "a", "b", "c" (one per line).
  130. my_csharp_node.PrintArray(["a", "b", "c"])
  131. # Output: "1", "2", "3" (one per line).
  132. my_csharp_node.PrintArray([1, 2, 3])
  133. Calling GDScript methods from C#
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  135. To call GDScript methods from C# you'll need to use
  136. :ref:`GodotObject.Call() <class_Object_method_call>`. The first argument is the
  137. name of the method you want to call. The following arguments will be passed
  138. to said method.
  139. .. code-block:: csharp
  140. // Output: "MyCSharpNode" (or name of node where this code is placed).
  141. myGDScriptNode.Call("print_node_name", this);
  142. // This line will fail silently and won't error out.
  143. // myGDScriptNode.Call("print_node_name");
  144. // Outputs "Hello there!" twice, once per line.
  145. myGDScriptNode.Call("print_n_times", "Hello there!", 2);
  146. string[] arr = new string[] { "a", "b", "c" };
  147. // Output: "a", "b", "c" (one per line).
  148. myGDScriptNode.Call("print_array", arr);
  149. // Output: "1", "2", "3" (one per line).
  150. myGDScriptNode.Call("print_array", new int[] { 1, 2, 3 });
  151. // Note how the type of each array entry does not matter
  152. // as long as it can be handled by the marshaller.
  153. .. _connecting_to_signals_cross_language:
  154. Connecting to signals
  155. ---------------------
  156. Connecting to C# signals from GDScript
  157. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  158. Connecting to a C# signal from GDScript is the same as connecting to a signal
  159. defined in GDScript:
  160. .. code-block:: gdscript
  161. my_csharp_node.MySignal.connect(my_signal_handler)
  162. Connecting to GDScript signals from C#
  163. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  164. Connecting to a GDScript signal from C# only works with the ``Connect`` method
  165. because no C# static types exist for signals defined by GDScript:
  166. .. code-block:: csharp
  167. myGDScriptNode.Connect("my_signal", Callable.From(MySignalHandler));
  168. Inheritance
  169. -----------
  170. A GDScript file may not inherit from a C# script. Likewise, a C# script may not
  171. inherit from a GDScript file. Due to how complex this would be to implement,
  172. this limitation is unlikely to be lifted in the future. See
  173. `this GitHub issue <https://github.com/godotengine/godot/issues/38352>`__
  174. for more information.