All Questions

Community

s
shahnj

Prefixing variables with an UNDERSCORE.

Hi,

Just to reinforce my understanding: when prefixing any variable with an _underscore, this will make the variable private within that script and or class and does not allow for it to be accessed and or modified in another script/class?

Is that correct?

Also, are there any subtleties or exceptions?

Thanks in advance!

  • GDQuestions replied

    It doesn't make the variable private: instead, it's a convention. It indicates teammates they should not use the variable outside the script.

    This is because GDScript doesn't have the notion of public and private built-in, unlike some other languages.

    Then, there's one particularity with function names with a leading underscore. The underscore is used for two conventions there:

    1. Pseudo-private functions (like variables, it means "you should not use this outside this script")
    2. Virtual functions (like Godot's _ready or _process).

    Virtual means the function does nothing by default and you have to redefine it in your code with code that does something. That's what you do when you create the _process or _ready function: you redefine an empty function that exists in Godot but doesn't do anything.

    Virtual functions are a way to predefine function names for someone else, like when Godot defines _ready and you use it.