icklesauce
icklesauce

Reputation: 11

Any GameObject.Find alternatives in Godot?

I cannot find anything after perusing the documentation (who knows I might've missed it), but I am trying to get access to a node in an existing scene and use it to set the position of the node getting it.

Perusing the documentation, finding a gameobject.find alternative, i did not find it.

Upvotes: 1

Views: 540

Answers (2)

Molbac
Molbac

Reputation: 81

You can add that one object to a group and then use

for gameObject in get_tree().get_nodes_in_group("group_name"):
    // do stuff with gameObject

documentation link

Upvotes: 0

Dustin_00
Dustin_00

Reputation: 455

I use a Global.cs with:

static Node Root;
public static void SetRoot(Node node) => Root = node;
public static T FindChild<T>(Node node = null)
{
    if (node is T t) return t;

    Godot.Collections.Array<Node> children = node is null ? Root.GetChildren() : node.GetChildren();
    foreach (var child in children)
    {
        T c = FindChild<T>(child);
        if (c is not null) return c;
    }
    
    return default;
}

For the node I want to find, I attach a unique script to the node (in the example below: NameLineEdit.cs)

Then in the first node that runs, set the root, then you can do find-by-type:

public override void _Ready()
{
    Global.SetRoot(GetNode("/root"));

    _nameLineEdit = Global.FindChild<NameLineEdit>();
}

The catch being that the first _Ready() will be a lowest child.

It's not ideal and I'd be interested in improvements that simplify this setup.

If you need a FindAll to grab a List, that should be fairly easy to add. I haven't done it because I only use this at app initialization to wire everything together.

Upvotes: 0

Related Questions