Get current node that the script is attached to

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Luka38
:warning: Old Version Published before Godot 3 was released.

I’m sorry for asking such a simple question, but I just can’t seem to find the answer.
How do you get the node that the current script is attached to, without using a name of the Node, since it won’t be the same because it will be duplicated.
I tried using get_owner(), but is just gives a null.
This seems like a very simple problem with a very simple solution, but I just can’t seem to find it :confused:
Thanks in advance!

:bust_in_silhouette: Reply From: Tapio Pyrhönen

You can use the keyword “self”.

Usually a script doesn’t need to find it’s node, because they are kinda one and the same thing. The keyword is handy sometimes, for example adding the node to an array that is contained in another scipt.

To add to Tapio’s correct answer: when you instance a node with a script, the scope of that script is that of the node, so for example calling get_position() will give you the position of that node. The same script can therefore be used for different nodes, and each will return their own position upon calling get_position() in that script.

As Tapio mentioned, when you need an explicit reference to the node, you can use self. It gives you a handle to the Node that you can pass to other objects (or, if you like things to be explicit, you can call self.get_position(), which is the same as get_position() alone but might be clearer to you).

You will typically need to use self when connecting signals from script via connect().

Akien | 2017-10-19 11:31

Thank you both for the replies!
I actually had some different problems with my code which made me think that accessing a node with just get_position()or something similar didn’t work.
But testing with print()solves most of the problems :smiley:

Luka38 | 2017-10-20 11:02

What if I want to attach the same script to multiple nodes and have it do different things.

For example, I have a node that spawns enemies or hazards on an endless runner. Depending on the node that the script is attached to (desert, jungle, city) it needs to spawn different enemies. Is there a way to get that information from script?

Tekuzo | 2020-06-09 20:06