+1 vote

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

in Engine by (19 points)

1 Answer

+4 votes

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.

by (3,886 points)
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.