+1 vote

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 :/
Thanks in advance!

asked Oct 19, 2017 in Engine by Luka38 (57 points)

1 Answer

+5 votes
Best answer

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.

answered Oct 19, 2017 by Tapio Pyrhönen (144 points)
selected Oct 20, 2017 by Luka38

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().

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 :D

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?

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.