c_sharp_features.rst 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. .. _doc_c_sharp_features:
  2. C# features
  3. ===========
  4. This page provides an overview of the commonly used features of both C# and Godot
  5. and how they are used together.
  6. .. _doc_c_sharp_features_type_conversion_and_casting:
  7. Type conversion and casting
  8. ---------------------------
  9. C# is a statically typed language. Therefore, you can't do the following:
  10. .. code-block:: csharp
  11. var mySprite = GetNode("MySprite");
  12. mySprite.SetFrame(0);
  13. The method ``GetNode()`` returns a ``Node`` instance.
  14. You must explicitly convert it to the desired derived type, ``Sprite2D`` in this case.
  15. For this, you have various options in C#.
  16. **Casting and Type Checking**
  17. Throws ``InvalidCastException`` if the returned node cannot be cast to Sprite2D.
  18. You would use it instead of the ``as`` operator if you are pretty sure it won't fail.
  19. .. code-block:: csharp
  20. Sprite2D mySprite = (Sprite2D)GetNode("MySprite");
  21. mySprite.SetFrame(0);
  22. **Using the AS operator**
  23. The ``as`` operator returns ``null`` if the node cannot be cast to Sprite2D,
  24. and for that reason, it cannot be used with value types.
  25. .. code-block:: csharp
  26. Sprite2D mySprite = GetNode("MySprite") as Sprite2D;
  27. // Only call SetFrame() if mySprite is not null
  28. mySprite?.SetFrame(0);
  29. **Using the generic methods**
  30. Generic methods are also provided to make this type conversion transparent.
  31. ``GetNode<T>()`` casts the node before returning it. It will throw an ``InvalidCastException`` if the node cannot be cast to the desired type.
  32. .. code-block:: csharp
  33. Sprite2D mySprite = GetNode<Sprite2D>("MySprite");
  34. mySprite.SetFrame(0);
  35. ``GetNodeOrNull<T>()`` uses the ``as`` operator and will return ``null`` if the node cannot be cast to the desired type.
  36. .. code-block:: csharp
  37. Sprite2D mySprite = GetNodeOrNull<Sprite2D>("MySprite");
  38. // Only call SetFrame() if mySprite is not null
  39. mySprite?.SetFrame(0);
  40. **Type checking using the IS operator**
  41. To check if the node can be cast to Sprite2D, you can use the ``is`` operator.
  42. The ``is`` operator returns false if the node cannot be cast to Sprite2D,
  43. otherwise it returns true. Note that when the ``is`` operator is used against ``null``
  44. the result is always going to be ``false``.
  45. .. code-block:: csharp
  46. if (GetNode("MySprite") is Sprite2D)
  47. {
  48. // Yup, it's a Sprite2D!
  49. }
  50. if (null is Sprite2D)
  51. {
  52. // This block can never happen.
  53. }
  54. You can also declare a new variable to conditionally store the result of the cast
  55. if the ``is`` operator returns ``true``.
  56. .. code-block:: csharp
  57. if (GetNode("MySprite") is Sprite2D mySprite)
  58. {
  59. // The mySprite variable only exists inside this block, and it's never null.
  60. mySprite.SetFrame(0);
  61. }
  62. For more advanced type checking, you can look into `Pattern Matching <https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching>`_.
  63. Preprocessor defines
  64. --------------------
  65. Godot has a set of defines that allow you to change your C# code
  66. depending on the environment you are compiling to.
  67. .. note:: If you created your project before Godot 3.2, you have to modify
  68. or regenerate your `csproj` file to use this feature
  69. (compare ``<DefineConstants>`` with a new 3.2+ project).
  70. Examples
  71. ~~~~~~~~
  72. For example, you can change code based on the platform:
  73. .. code-block:: csharp
  74. public override void _Ready()
  75. {
  76. #if GODOT_SERVER
  77. // Don't try to load meshes or anything, this is a server!
  78. LaunchServer();
  79. #elif GODOT_32 || GODOT_MOBILE || GODOT_WEB
  80. // Use simple objects when running on less powerful systems.
  81. SpawnSimpleObjects();
  82. #else
  83. SpawnComplexObjects();
  84. #endif
  85. }
  86. Or you can detect which engine your code is in, useful for making cross-engine libraries:
  87. .. code-block:: csharp
  88. public void MyPlatformPrinter()
  89. {
  90. #if GODOT
  91. GD.Print("This is Godot.");
  92. #elif UNITY_5_3_OR_NEWER
  93. print("This is Unity.");
  94. #else
  95. throw new NotSupportedException("Only Godot and Unity are supported.");
  96. #endif
  97. }
  98. Or you can write scripts that target multiple Godot versions and can take
  99. advantage that are only available on some of those versions:
  100. .. code-block:: csharp
  101. public void UseCoolFeature()
  102. {
  103. #if GODOT4_3_OR_GREATER || GODOT4_2_2_OR_GREATER
  104. // Use CoolFeature, that was added to Godot in 4.3 and cherry-picked into 4.2.2, here.
  105. #else
  106. // Use a workaround for the absence of CoolFeature here.
  107. #endif
  108. }
  109. Full list of defines
  110. ~~~~~~~~~~~~~~~~~~~~
  111. * ``GODOT`` is always defined for Godot projects.
  112. * ``TOOLS`` is defined when building with the Debug configuration (editor and editor player).
  113. * ``GODOT_REAL_T_IS_DOUBLE`` is defined when the ``GodotFloat64`` property is set to ``true``.
  114. * One of ``GODOT_64`` or ``GODOT_32`` is defined depending on if the architecture is 64-bit or 32-bit.
  115. * One of ``GODOT_LINUXBSD``, ``GODOT_WINDOWS``, ``GODOT_OSX``,
  116. ``GODOT_ANDROID``, ``GODOT_IOS``, ``GODOT_HTML5``, or ``GODOT_SERVER``
  117. depending on the OS. These names may change in the future.
  118. These are created from the ``get_name()`` method of the
  119. :ref:`OS <class_OS>` singleton, but not every possible OS
  120. the method returns is an OS that Godot with .NET runs on.
  121. * ``GODOTX``, ``GODOTX_Y``, ``GODOTX_Y_Z``, ``GODOTx_OR_GREATER``,
  122. ``GODOTX_y_OR_GREATER``, and ``GODOTX_Y_z_OR_GREATER``, where ``X``, ``Y``,
  123. and ``Z`` are replaced by the current major, minor and patch version of Godot.
  124. ``x``, ``y``, and ``z`` are replaced by 0 to to the current version for that
  125. component.
  126. .. note::
  127. These defines were first added in Godot 4.0.4 and 4.1. Version defines for
  128. prior versions do not exist, regardless of the current Godot version.
  129. For example: Godot 4.0.5 defines ``GODOT4``, ``GODOT4_OR_GREATER``,
  130. ``GODOT4_0``, ``GODOT4_0_OR_GREATER``, ``GODOT4_0_5``,
  131. ``GODOT4_0_4_OR_GREATER``, and ``GODOT4_0_5_OR_GREATER``. Godot 4.3.2 defines
  132. ``GODOT4``, ``GODOT4_OR_GREATER``, ``GODOT4_3``, ``GODOT4_0_OR_GREATER``,
  133. ``GODOT4_1_OR_GREATER``, ``GODOT4_2_OR_GREATER``, ``GODOT4_3_OR_GREATER``,
  134. ``GODOT4_3_2``, ``GODOT4_3_0_OR_GREATER``, ``GODOT4_3_1_OR_GREATER``, and
  135. ``GODOT4_3_2_OR_GREATER``.
  136. When **exporting**, the following may also be defined depending on the export features:
  137. * One of ``GODOT_PC``, ``GODOT_MOBILE``, or ``GODOT_WEB`` depending on the platform type.
  138. * One of ``GODOT_WINDOWS``, ``GODOT_LINUXBSD``, ``GODOT_MACOS``, ``GODOT_UWP``, ``GODOT_HAIKU``, ``GODOT_ANDROID``, ``GODOT_IOS``, or ``GODOT_WEB`` depending on the platform.
  139. To see an example project, see the OS testing demo:
  140. https://github.com/godotengine/godot-demo-projects/tree/master/misc/os_test