find all spatial children in a kinematicbody node in csharp

You can find all the spatial children of a KinematicBody node in Godot using C# code with the following steps:

  1. Get a reference to the KinematicBody node you want to check. You can do this using the GetNode method, like this:
main.cs
KinematicBody kinematicBody = GetNode<KinematicBody>("kinematic_body");
72 chars
2 lines
  1. Iterate through all the children of the KinematicBody node using a foreach loop. You can use the GetChildCount and GetChild methods for this:
main.cs
foreach (Node child in kinematicBody.GetChildren()) {
    // Do something with child node
}
92 chars
4 lines
  1. Check if each child node is a Spatial node using the is keyword:
main.cs
foreach (Node child in kinematicBody.GetChildren()) {
    if (child is Spatial) {
        // Do something with spatial child node
    }
}
138 chars
6 lines

Putting it all together, the complete code to find all the spatial children of a KinematicBody node looks like this:

main.cs
KinematicBody kinematicBody = GetNode<KinematicBody>("kinematic_body");

foreach (Node child in kinematicBody.GetChildren()) {
    if (child is Spatial) {
        Spatial spatialChild = (Spatial)child;
        // Do something with spatial child node
    }
}
258 chars
9 lines

gistlibby LogSnag