You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Babushka/scripts/CSharp/Common/Util/NodeExtension.cs

78 lines
2.4 KiB

using System;
using System.Collections.Generic;
using Godot;
namespace Babushka.scripts.CSharp.Common.Util;
public static class NodeExtension
{
/// <summary>
/// Searches for a parent node of the specified type.
/// </summary>
/// <typeparam name="T">The type of the parent node to search for. The search is successful, when <code>searchedNode is T</code></typeparam>
/// <param name="self">The node from which to start the search.</param>
/// <returns>The parent node of type T if found, otherwise throws an exception.</returns>
public static T FindParentByType<T>(this Node self)
{
var parent = self.GetParent();
while (parent != null)
{
if (parent is T tParent)
{
return tParent;
}
parent = parent.GetParent();
}
throw new Exception($"Parent of type {typeof(T)} not found for node {self.Name}");
}
//acts like Unity's GetComponent<T> / GetComponentInChildren<T>
// only works with Godot's built-in types.
public static T GetChildByType<T>(this Node node, bool recursive = true)
where T : Node
{
int childCount = node.GetChildCount();
for (int i = 0; i < childCount; i++)
{
Node child = node.GetChild(i);
if (child is T childT)
return childT;
if (recursive && child.GetChildCount() > 0)
{
T recursiveResult = child.GetChildByType<T>(true);
if (recursiveResult != null)
return recursiveResult;
}
}
return null;
}
/// <summary>
/// Another reimplementation of Unity's GetComponent<T>.
/// Verified to work with all types, also derived ones, but only when used from within a scene and at runtime.
/// </summary>
/// <param name="node"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetComponent<T>(Node node)
{
if (node is T)
{
return (T)(object)node;
}
foreach (Node child in node.GetChildren())
{
if (child is T)
{
return (T)(object)child;
}
}
return (T)(object)null;
}
}