GD Script _ conventions

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jarlowrey
:warning: Old Version Published before Godot 3 was released.

Looking over some of the examples I’ve noticed a lot of functions begin with a “_”, why is that? I found this unofficial style guide, but it doesn’t mention anything about when functions should begin with an underscore.

:bust_in_silhouette: Reply From: Pavel Kotlyar

_ is for a private or protected method of class (script), that’s mean when you have an instance of Class (node script) you will not get access to the private method when calling from outside. So for example you have a scene with GDScript attached

var your_node = load("res://scenes/your_node.tscn").instance()
your_node.some_public_method_defined()

however you will not be able to call a method defined with _ in the script from the instance, so if you have func _some_method_defined(): defined in your script, the next will not work:

var your_node = load("res://scenes/your_node.tscn").instance()
your_node._some_method_defined()

It helps to design your classes more clear in terms of what should be accessible outside and what is only for private class use.

:bust_in_silhouette: Reply From: sg7

According to GDScript Style Guide 3.x prepend a single underscore (_) to

  • virtual methods (functions the user must override)
  • private functions
  • private variables

Now you can realize why func _ready() has the underscore at the beginning of the name. In this case the func _ready() is a virtual function which user can define for his needs.

In the same way (by adding the “_” underscore) you can make your script(class) variables private. They will not be accessible from other scripts.