2
0

cross_language_scripting.rst 7.1 KB

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