What is "self" used for?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By deathgm

I have some “self” troubles, can someone explain it to me in a specific way? Thank you very much!

:bust_in_silhouette: Reply From: kidscancode

self is used to get a reference to the current node (ie the one the script is attached to.

Here’s an example:

extends Node2D

func _ready():
    $Button.connect("pressed", self, "_on_Button_pressed")

func _on_Button_pressed():
    print("Button was pressed")

The connect() code connects the pressed signal from the child node named “Button”, to the named function on the destination node (self).

Note that self is implicit, and so isn’t needed when calling local methods or accessing local properties:

print(self.position)

is equivalent to

print(position)

You only really need to explicitly use self when you specifically need a reference, as in the above example.

Thanks, I finally understand it

deathgm | 2020-03-09 17:04