What is self in GDscript

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

I wanna know what is meaning of self in gd script and how it works(Use example please)

:bust_in_silhouette: Reply From: timothybrentwood

It’s similar to this in other languages. It give you a reference to the object that the current script is attached to then allows you to access a member variable or function on it.

onready var my_sprite = get_node("Sprite") #alternatively $Sprite

func _ready():
    my_sprite.scale = some_scale_vector

So above my_sprite is a reference to the child node Sprite. Much in the same way self is a reference to the node that the current script is attached to, as mentioned above.

var my_var = 0 setget set_my_var, get_my_var

func set_my_var(value):
    my_var = min(value, 50)

func get_my_var():
    return 100

func _ready()
    print(my_var) # prints 0

    for i in range(65):
        my_var = my_var + 1

    print(my_var) # prints 65

    my_var = 0

    for i in range(65):
        self.my_var = my_var + 1 # calls set_my_var(value)

    print(my_var) # prints 50

    print(self.my_var) # prints 100, calls get_my_var()

The useful thing about using self is that it always calls the setter and getter functions associated with variables from within the script. There is a slight performance hit to using self but it’s negligible, in general you want to access the member variables/functions directly unless there is a setter and getter associated with them. I do believe this requirement is going away with Godot 4.0 and it will always call the setters and getters regardless if they are accessed with self or not, but I’m not certain.