All Questions

Community

S
nodeg

Why is this a class?

I know there's a good chance this will become clear in a later video, but why are we making the player scene a class? What are the advantages?

  • Nathan Lovato replied
    Solution

    Any GDScript file is a class. Class_name just gives it a name we can access globally in the project.

    Here are several reasons to do that:

    • If you name your classes, you'll get an error when you name two classes the same, helping you avoid making that mistake in your project.
    • You can use that class as a type hint. Imagine a system that passes the player node to the UI to initialize it. You can write a line like:
    onready var player: Player = get_node("Level/Player")
    

    And you'll get full auto-completion for it. The type checker will also ensure that the node "Level/Player" is of type Player.

    For something like our player, that's mostly it. In other cases, it allows you to directly create a node of that type in the editor, if that GDScript class doesn't depends on its scene. That is to say, if it doesn't have other nodes as a dependency that are saved in a tscn file.