Search code examples
c#godot

GODOT - C# referencing current node


I have specific problem in coding in GODOT(I'm using C#, I'm new to godot). I need to reference current node that has attached script. Let's say - I have 3 buttons and all of them inherits from base class called "menuButton" that has attached script called "menuScript" that includes code for changing text color onHover. And I need to reference current node, so that I can change the color of child label node.


Solution

  • Some examples, there may be more combinations:

    private CollisionShape2D charCollider;
    private Node3D child1; //godot4 new name
    [Export] public NodePath characterPath; //this define on editor
    private Control control;
    private Camera camera;
    
    public override void _Ready(){
        //by string path 
        char_collider = (CollisionShape2D) GetNode("child0/char_collider"); 
        //by child index or null if no exists second child 
        child1 = GetChildOrNull<Node3D>(1);
        //by nodePath with editor
        control = GetNodeOrNull<Control>(characterPath);
        //"this" is not necessary but work
        var node = this.GetNode("banana") as Node;
        //you can use "parent()" or ("../..")
        camera = node.GetParent();
        camera= node.GetNode("..");//same
        //Any Node inheritance can use these functions
        node = camera.GetNode("child");
        //You can use uniques names on editor
        GetNode<Button>("%buPlay").Pressed += onClickPlay;
    }