cross_language_scripting.rst 7.1 KB

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