c_sharp_features.rst 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. .. _doc_c_sharp_features:
  2. 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. Type conversion and casting
  7. ---------------------------
  8. C# is a statically typed language. Therefore, you can't do the following:
  9. .. code-block:: csharp
  10. var mySprite = GetNode("MySprite");
  11. mySprite.SetFrame(0);
  12. The method ``GetNode()`` returns a ``Node`` instance.
  13. You must explicitly convert it to the desired derived type, ``Sprite`` in this case.
  14. For this, you have various options in C#.
  15. **Casting and Type Checking**
  16. Throws ``InvalidCastException`` if the returned node cannot be cast to Sprite.
  17. You would use it instead of the ``as`` operator if you are pretty sure it won't fail.
  18. .. code-block:: csharp
  19. Sprite mySprite = (Sprite)GetNode("MySprite");
  20. mySprite.SetFrame(0);
  21. **Using the AS operator**
  22. The ``as`` operator returns null if the node cannot be cast to Sprite,
  23. and for that reason, it cannot be used with value types.
  24. .. code-block:: csharp
  25. Sprite mySprite = GetNode("MySprite") as Sprite;
  26. // Only call SetFrame() if mySprite is not null
  27. mySprite?.SetFrame(0);
  28. **Using the generic methods**
  29. Generic methods are also provided to make this type conversion transparent.
  30. ``GetNode<T>()`` casts the node before returning it. It will throw an ``InvalidCastException`` if the node cannot be cast to the desired type.
  31. .. code-block:: csharp
  32. Sprite mySprite = GetNode<Sprite>("MySprite");
  33. mySprite.SetFrame(0);
  34. ``GetNodeOrNull<T>()`` uses the ``as`` operator and will return ``null`` if the node cannot be cast to the desired type.
  35. .. code-block:: csharp
  36. Sprite mySprite = GetNodeOrNull<Sprite>("MySprite");
  37. // Only call SetFrame() if mySprite is not null
  38. mySprite?.SetFrame(0);
  39. **Type checking using the IS operator**
  40. To check if the node can be cast to Sprite, you can use the ``is`` operator.
  41. The ``is`` operator returns false if the node cannot be cast to Sprite,
  42. otherwise it returns true.
  43. .. code-block:: csharp
  44. if (GetNode("MySprite") is Sprite)
  45. {
  46. // Yup, it's a sprite!
  47. }
  48. For more advanced type checking, you can look into `Pattern Matching <https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching>`_.
  49. .. _c_sharp_signals:
  50. C# signals
  51. ----------
  52. For a complete C# example, see the **Handling a signal** section in the step by step :ref:`doc_scripting` tutorial.
  53. Declaring a signal in C# is done with the ``[Signal]`` attribute on a delegate.
  54. .. code-block:: csharp
  55. [Signal]
  56. delegate void MySignal();
  57. [Signal]
  58. delegate void MySignalWithArguments(string foo, int bar);
  59. These signals can then be connected either in the editor or from code with ``Connect``.
  60. .. code-block:: csharp
  61. public void MyCallback()
  62. {
  63. GD.Print("My callback!");
  64. }
  65. public void MyCallbackWithArguments(string foo, int bar)
  66. {
  67. GD.Print("My callback with: ", foo, " and ", bar, "!");
  68. }
  69. public void SomeFunction()
  70. {
  71. instance.Connect("MySignal", this, "MyCallback");
  72. instance.Connect(nameof(MySignalWithArguments), this, "MyCallbackWithArguments");
  73. }
  74. Emitting signals is done with the ``EmitSignal`` method.
  75. .. code-block:: csharp
  76. public void SomeFunction()
  77. {
  78. EmitSignal(nameof(MySignal));
  79. EmitSignal("MySignalWithArguments", "hello there", 28);
  80. }
  81. Notice that you can always reference a signal name with the ``nameof`` keyword (applied on the delegate itself).
  82. It is possible to bind values when establishing a connection by passing an object array.
  83. .. code-block:: csharp
  84. public int Value { get; private set; } = 0;
  85. private void ModifyValue(int modifier)
  86. {
  87. Value += modifier;
  88. }
  89. public void SomeFunction()
  90. {
  91. var plusButton = (Button)GetNode("PlusButton");
  92. var minusButton = (Button)GetNode("MinusButton");
  93. plusButton.Connect("pressed", this, "ModifyValue", new object[] { 1 });
  94. minusButton.Connect("pressed", this, "ModifyValue", new object[] { -1 });
  95. }
  96. Signals support parameters and bound values of all the `built-in types <https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table>`_ and Classes derived from :ref:`Godot.Object <class_Object>`.
  97. Consequently, any ``Node`` or ``Reference`` will be compatible automatically, but custom data objects will need to extend from `Godot.Object` or one of its subclasses.
  98. .. code-block:: csharp
  99. public class DataObject : Godot.Object
  100. {
  101. public string Field1 { get; set; }
  102. public string Field2 { get; set; }
  103. }
  104. Finally, signals can be created by calling ``AddUserSignal``, but be aware that it should be executed before any use of said signals (with ``Connect`` or ``EmitSignal``).
  105. .. code-block:: csharp
  106. public void SomeFunction()
  107. {
  108. AddUserSignal("MyOtherSignal");
  109. EmitSignal("MyOtherSignal");
  110. }