Add C# code examples (salvage of VinnNo's PRs)

This commit is contained in:
Aaron Franke
2021-09-09 12:15:28 -05:00
parent c1b7505ef8
commit da14b8000d
7 changed files with 434 additions and 97 deletions

View File

@@ -161,8 +161,8 @@ it as if it was an image (via :ref:`ViewportContainer <class_ViewportContainer>`
Creating custom Containers
--------------------------
It is possible to easily create a custom container using script. Here is an example of a container that fits children
to its rect size:
It is possible to create a custom container using a script.
Here is an example of a container that fits children to its rect size:
.. tabs::
.. code-tab:: gdscript GDScript
@@ -174,8 +174,34 @@ to its rect size:
# Must re-sort the children
for c in get_children():
# Fit to own size
fit_child_in_rect( c, Rect2( Vector2(), rect_size ) )
fit_child_in_rect(c, Rect2(Vector2(), rect_size))
func set_some_setting():
# Some setting changed, ask for children re-sort
# Some setting changed, ask for children re-sort.
queue_sort()
.. code-tab:: csharp
using Godot;
public class CustomContainer : Container
{
public override void _Notification(int what)
{
if (what == NotificationSortChildren)
{
// Must re-sort the children
foreach (Control c in GetChildren())
{
// Fit to own size
FitChildInRect(c, new Rect2(new Vector2(), RectSize));
}
}
}
public void SetSomeSetting()
{
// Some setting changed, ask for children re-sort.
QueueSort();
}
}

View File

@@ -63,7 +63,8 @@ To center a control in its parent, set its anchors to 0.5 and each margin
to half of its relevant dimension. For example, the code below shows how
a TextureRect can be centered in its parent:
::
.. tabs::
.. code-tab:: gdscript GDScript
var rect = TextureRect.new()
rect.texture = load("res://icon.png")
@@ -72,12 +73,30 @@ a TextureRect can be centered in its parent:
rect.anchor_top = 0.5
rect.anchor_bottom = 0.5
var texture_size = rect.texture.get_size()
rect.margin_left = -texture_size.x / 2
rect.margin_right = -texture_size.x / 2
rect.margin_top = -texture_size.y / 2
rect.margin_bottom = -texture_size.y / 2
rect.offset_left = -texture_size.x / 2
rect.offset_right = texture_size.x / 2
rect.offset_top = -texture_size.y / 2
rect.offset_bottom = texture_size.y / 2
add_child(rect)
.. code-tab:: csharp
var rect = new TextureRect();
rect.Texture = ResourceLoader.Load<Texture>("res://icon.png");
rect.AnchorLeft = 0.5f;
rect.AnchorRight = 0.5f;
rect.AnchorTop = 0.5f;
rect.AnchorBottom = 0.5f;
var textureSize = rect.Texture.GetSize();
rect.OffsetLeft = -textureSize.x / 2;
rect.OffsetRight = textureSize.x / 2;
rect.OffsetTop = -textureSize.y / 2;
rect.OffsetBottom = textureSize.y / 2;
AddChild(rect);
Setting each anchor to 0.5 moves the reference point for the margins to
the center of its parent. From there, we set negative margins so that
the control gets its natural size.