Godot.Sharp.Extended/Core/Tools/NodeExtensions.cs
Mario Steele b4a2ce40c1 Added Core Functionality
Added core functionality that was from the old Godot.Sharp.Extra library.  Not all functions, only functions that were considered worth porting.
2025-09-26 20:12:37 -05:00

65 lines
No EOL
1.8 KiB
C#

using Godot.Collections;
namespace Godot.Sharp.Extended.Tools;
public static class NodeExtensions
{
public static void AddToGroup(this Node node) => node.AddToGroup(node.GetType().Name);
public static T GetNode<T>(this Node node) where T : Node => node.GetNode<T>(typeof(T).Name);
public static Array<T> GetChildrenOfType<T>(this Node node) where T : Node
{
var children = node.GetChildren();
return new Array<T>(children.OfType<T>().ToArray());
}
public static T? GetFirstChildOfType<T>(this Node node) where T : Node => GetChildrenOfType<T>(node).FirstOrDefault();
public static void RemoveAllChildren(this Node node)
{
foreach (var child in node.GetChildren())
node.RemoveChild(child);
}
public static void RemoveAndQueueFreeChildren(this Node node)
{
foreach (var child in node.GetChildren())
{
node.RemoveChild(child);
child.QueueFree();
}
}
public static void QueueFreeChildren(this Node node)
{
foreach (var child in node.GetChildren())
node.QueueFree();
}
public static T? GetAncestor<T>(this Node node) where T : Node
{
Node current = node;
Node root = node.GetTree().Root;
while (current != root && !(current is T))
current = current.GetParent();
return current as T;
}
public static Node? GetLastChild(this Node node)
{
var count = node.GetChildCount();
if (count == 0) return null;
return node.GetChild(count - 1);
}
public static T? GetLastChild<T>(this Node node) where T : Node
{
Node? last = null;
foreach (var child in node.GetChildren())
{
if (child is T) last = child;
}
return last as T;
}
}