cross_language_scripting.rst 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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_field: String = "foo"
  13. signal my_signal
  14. signal my_signal_with_params(msg: String, n: int)
  15. func print_node_name(node: Node) -> void:
  16. print(node.get_name())
  17. func print_array(arr: Array) -> void:
  18. for element in arr:
  19. print(element)
  20. func print_n_times(msg: String, n: int) -> void:
  21. for i in range(n):
  22. print(msg)
  23. func my_signal_handler():
  24. print("The signal handler was called!")
  25. func my_signal_with_params_handler(msg: String, n: int):
  26. print_n_times(msg, n)
  27. .. code-tab:: csharp
  28. using Godot;
  29. public partial class MyCSharpNode : Node
  30. {
  31. public string myField = "bar";
  32. [Signal] public delegate void MySignalEventHandler();
  33. [Signal] public delegate void MySignalWithParamsEventHandler(string msg, int n);
  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. public void MySignalWithParamsHandler(string msg, int n)
  57. {
  58. PrintNTimes(msg, n);
  59. }
  60. }
  61. Instantiating nodes
  62. -------------------
  63. If you're not using nodes from the scene tree, you'll probably want to
  64. instantiate nodes directly from the code.
  65. Instantiating C# nodes from GDScript
  66. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  67. Using C# from GDScript doesn't need much work. Once loaded
  68. (see :ref:`doc_gdscript_classes_as_resources`), the script can be instantiated
  69. with :ref:`new() <class_CSharpScript_method_new>`.
  70. .. code-block:: gdscript
  71. var my_csharp_script = load("res://Path/To/MyCSharpNode.cs")
  72. var my_csharp_node = my_csharp_script.new()
  73. .. warning::
  74. When creating ``.cs`` scripts, you should always keep in mind that the class
  75. Godot will use is the one named like the ``.cs`` file itself. If that class
  76. does not exist in the file, you'll see the following error:
  77. ``Invalid call. Nonexistent function `new` in base``.
  78. For example, MyCoolNode.cs should contain a class named MyCoolNode.
  79. The C# class needs to derive a Godot class, for example ``GodotObject``.
  80. Otherwise, the same error will occur.
  81. You also need to check your ``.cs`` file is referenced in the project's
  82. ``.csproj`` file. Otherwise, the same error will occur.
  83. Instantiating GDScript nodes from C#
  84. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  85. From the C# side, everything work the same way. Once loaded, the GDScript can
  86. be instantiated with :ref:`GDScript.New() <class_GDScript_method_new>`.
  87. .. code-block:: csharp
  88. GDScript MyGDScript = GD.Load<GDScript>("res://path/to/my_gd_script.gd");
  89. GodotObject myGDScriptNode = (GodotObject)MyGDScript.New(); // This is a GodotObject.
  90. Here we are using an :ref:`class_Object`, but you can use type conversion like
  91. explained in :ref:`doc_c_sharp_features_type_conversion_and_casting`.
  92. Accessing fields
  93. ----------------
  94. Accessing C# fields from GDScript
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. Accessing C# fields from GDScript is straightforward, you shouldn't have
  97. anything to worry about.
  98. .. code-block:: gdscript
  99. print(my_csharp_node.myField) # bar
  100. my_csharp_node.myField = "BAR"
  101. print(my_csharp_node.myField) # BAR
  102. Accessing GDScript fields from C#
  103. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  104. As C# is statically typed, accessing GDScript from C# is a bit more
  105. convoluted, you will have to use :ref:`GodotObject.Get() <class_Object_method_get>`
  106. and :ref:`GodotObject.Set() <class_Object_method_set>`. The first argument is the name of the field you want to access.
  107. .. code-block:: csharp
  108. GD.Print(myGDScriptNode.Get("my_field")); // foo
  109. myGDScriptNode.Set("my_field", "FOO");
  110. GD.Print(myGDScriptNode.Get("my_field")); // FOO
  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. my_csharp_node.PrintNodeName(self) # myGDScriptNode
  124. # my_csharp_node.PrintNodeName() # This line will fail.
  125. my_csharp_node.PrintNTimes("Hello there!", 2) # Hello there! Hello there!
  126. my_csharp_node.PrintArray(["a", "b", "c"]) # a, b, c
  127. my_csharp_node.PrintArray([1, 2, 3]) # 1, 2, 3
  128. Calling GDScript methods from C#
  129. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  130. To call GDScript methods from C# you'll need to use
  131. :ref:`GodotObject.Call() <class_Object_method_call>`. The first argument is the
  132. name of the method you want to call. The following arguments will be passed
  133. to said method.
  134. .. code-block:: csharp
  135. myGDScriptNode.Call("print_node_name", this); // my_csharp_node
  136. // myGDScriptNode.Call("print_node_name"); // This line will fail silently and won't error out.
  137. myGDScriptNode.Call("print_n_times", "Hello there!", 2); // Hello there! Hello there!
  138. string[] arr = new string[] { "a", "b", "c" };
  139. myGDScriptNode.Call("print_array", arr); // a, b, c
  140. myGDScriptNode.Call("print_array", new int[] { 1, 2, 3 }); // 1, 2, 3
  141. // Note how the type of each array entry does not matter as long as it can be handled by the marshaller.
  142. .. warning::
  143. As you can see, if the first argument of the called method is an array,
  144. you'll need to cast it as ``object``.
  145. Otherwise, each element of your array will be treated as a single argument
  146. and the function signature won't match.
  147. .. _connecting_to_signals_cross_language:
  148. Connecting to signals
  149. ---------------------
  150. Connecting to C# signals from GDScript
  151. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  152. Connecting to a C# signal from GDScript is the same as connecting to a signal
  153. defined in GDScript:
  154. .. code-block:: gdscript
  155. my_csharp_node.MySignal.connect(my_signal_handler)
  156. my_csharp_node.MySignalWithParams.connect(my_signal_with_params_handler)
  157. Connecting to GDScript signals from C#
  158. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  159. Connecting to a GDScript signal from C# only works with the ``Connect`` method
  160. because no C# static types exist for signals defined by GDScript:
  161. .. code-block:: csharp
  162. myGDScriptNode.Connect("my_signal", Callable.From(MySignalHandler));
  163. myGDScriptNode.Connect("my_signal_with_params", Callable.From<string, int>(MySignalWithParamsHandler));
  164. Inheritance
  165. -----------
  166. A GDScript file may not inherit from a C# script. Likewise, a C# script may not
  167. inherit from a GDScript file. Due to how complex this would be to implement,
  168. this limitation is unlikely to be lifted in the future. See
  169. `this GitHub issue <https://github.com/godotengine/godot/issues/38352>`__
  170. for more information.