+8 votes

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!

in Engine by (64 points)

1 Answer

+12 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.

by (154 points)
selected by

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.