Is there way to access node's method from other node's child?

Godot Version

4.2

Question

Lets say I have tree like this:

Main
---Node1
---Node2
    |---Child

I want to access a method on Node1 from Child but if try I’m getting “null instance” error. Is there a way how to do that?

@onready var node1 = $"../Node1"
func _ready():
	Node1.printHello()

It seems like this is the way:
@onready var node1 = $“…/…/Node1”
But I have a feeling there is much better option, isnt there?

Seems like a great use case for the Unique Name feature.

Also in your code you’re initialising as node1 and then trying to access as Node1 (but that may just be a typo in your example).

Simplified setup

Have just tested with this:

extends Node2D
#on node 1
func SayHello():
	print("Hello, world!")

and

extends Node2D
#on node 2
func _ready():
	%Node1.SayHello()

and it works.
Scene Tree looks like:
┖╴Main
  ┠╴Node1
  ┖╴Node2

Have also tried with:

func _ready():
	$"../Node1".SayHello()

Also tried with:


@onready var test = $"../Node1"
func _ready():
	test.SayHello()

A setup a bit more like your original:

main
┖╴Main
  ┠╴Node1
  ┖╴Node2
    ┖╴Node3

This again works with the script now on Node3 using unique accessor name, accessing function in Node1 - you can use:

$"../../Node1".SayHello()

but I can see this getting out of hand quickly.

The script is on a child of Node2, it’s like michal said.

You could also use
get_parent().get_parent().get_node(“Node1”).printHello()
Or alternatively
get_tree().current_scene.get_node(“Node1”).printHello()

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.